编译:$clang - rewrite -objc main.m
消息发送机制 Person *p = [[Person alloc] init];
import <objc/message.h>
//iOS5苹果不建议使用底层方法,需要在Build Phases搜索msg设置
Person *p = [Person new];
objc_msgsend(p,@selector(run));
objc_msgsend(p,@selecor(eatFood:),@"fruit");
Class PersonClass = [Person class];
类方法:objc_msgsend(PersonClass, @selector(类方法),参数);
类也是特殊对象,等同[PersonClass performSelector:@selector(run)];
Runtime应用场景
- 归档/解档:序列化/反序列化 object以键值对的形式保存成二进制文件
for(int i = 0, i < 属性的个数, i++) {
[Coder encodeObject:属性值 forKey:key];
}
//Ivar:runtime里面Ivar代表属性成员变量 unsigned int count = 0;
//im 中成员变量也可以拿到
//书 Objective_C 2.0 运行时系统编程指南
Ivar *ivars = Class_copyIvarList([Person class], & count); =
Ivar ivar = ivars[0]; const char *name = ivar_getName(ivar);
#import<objc/message.h>
//归档
- (void)encodeWithCoder:(NSCoder *)coder {
unsigned int count = 0;
Ivar *ivars = Class_copyIvarList([Person class], &count);
for (int i = 0; i < count; i++) {
Ivar *ivars = class_copyIvarList([Person Class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
[coder encodeObject:[self valueForKey:key] forKey:key];
}
free(ivars);
}
}
//解档
- (instancetype)initWithCoder:(NSCoder *)coder {
if (self = [super init]) {
unsigned int count = 0;
Ivar *ivars = Class_copyIvarList([Person class], &count);
for (int i = 0; i < count; i++) {
Ivar *ivars = class_copyIvarList([Person Class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
id value = [coder decodeObjectForKey:key];
[self setValue:value forKey:key];
}
free(ivars);
}
}
}