消息发送机制

C语言在编译时候就知道了一会要调用的函数

OC是运行时才能知道要调用哪个方法和函数

OC方法调用可转化为C的消息发送    

新建一个工程,创建一个Student类:

//  Student.h

#import <Foundation/Foundation.h>

@interface Student : NSObject
+ (void)backHome;
- (void)study;
- (void)gotoSchoolWith:(NSString *)book;
@end

//  Student.m

#import "Student.h"

@implementation Student

+ (void)backHome{
    NSLog(@"这是类方法");
}

- (void)study{
    NSLog(@"在学习");
}

- (void)gotoSchoolWith:(NSString *)book{
    NSLog(@"带%@课本去上学",book);
}

@end

在ViewController.m中引入头文件

//  ViewController.m

#import "ViewController.h"
#import <objc/message.h>  //一定要引入
#import "Student.h"

在viewDidload中做如下实现

- (void)viewDidLoad {
    [super viewDidLoad];
    Student *s = [[Student alloc]init];//初始化一个学生对象
    
    //OC方法调用
    [s study];
    //performSelector 也是OC方法,不推荐用,不安全,方法名错时不会报错
    [s performSelector:@selector(study)];
    [s performSelector:@selector(gotoSchoolWith:) withObject:@"数学"];
    //类方法
    Class sClass = [Student class];//类类型
    [sClass performSelector:@selector(backHome)];//类方法没有自动补齐要自己敲
    
    
    //让s发一个study消息,后边可接多参数,这里与上述OC方法完全一致
    objc_msgSend(s, @selector(study));
    objc_msgSend(s, @selector(gotoSchoolWith:),@"语文");
    objc_msgSend(sClass, @selector(backHome));//类方法
    
}

注意:从Xcode5开始,苹果不建议使用底层函数,需要手动设置下图所示位置配置为NO,方可使用objc_msgSend()



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值