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()