Objective-C runtime
是一个实现Objective-C语言的C库。对象可以用C语言中的结构体表示,而方法(methods
)可以用C函数实现。事实上,他们 差不多也是这么干了,另外再加上了一些额外的特性。这些结构体和函数被runtime
函数封装后,Objective-C程序员可以在程序运行时创建,检查,修改类,对象和它们的方法。
除了封装,Objective-C runtime
库也负责找出方法的最终执行代码。当程序执行[object doSomething]
时,不会直接找到方法并调用。相反,一条消息(message
)会发送给对象(在这儿,我们通常叫它接收者)。runtime
库会给次机会让对象根据消息决定该作出什么样的反应。
如下是部分runtime
常用的方法整理:
动态创建类, 添加成员变量, 赋值并调用动态添加的方法
- (void)viewDidLoad {
[super viewDidLoad];
// 动态创建People类, 继承自NSObject类
// 额外空间 未知,通常设置为 0
Class People = objc_allocateClassPair([NSObject class], "Person", 0);
// 以NSString*为例
// 变量size sizeof(NSString)
// 对齐 指针类型的为log2(sizeof(NSString*))
// 类型 @encode(NSString*)
// 添加_name 成员变量
BOOL flag1 = class_addIvar([People class], "_name", sizeof(NSString *), log2(sizeof(NSString *)), @encode(NSString *));
if (flag1) {
NSLog(@"添加成员变量_name成功!");
}
// 添加_age 成员变量
BOOL flag2 = class_addIvar([People class], "_age", sizeof(int), sizeof(int), @encode(int));
if (flag2) {
NSLog(@"添加成员变量_age成功!");
}
// 注册方法名为say:的方法
SEL s = sel_registerName("say:");
// 添加say:方法的实现
// "v@:@"
// v表示返回值为void, i表示返回值为int
// @表示参数id(self)
// :表示SEL(_cmd)
// @表示id
class_addMethod([People class], s, (IMP)sayFunction1, "v@:@");
// 注册该类
objc_registerClassPair([People class]);
// 创建类的实例
id peopleInstance = [[People alloc] init];
// KVC 动态改变 对象peopleInstance 中的实例变量
[peopleInstance setValue:@"老师" forKey:@"name"];
// Ivar nameVar = class_getInstanceVariable([People class], "_name");
// object_setIvar(peopleInstance, nameVar, @"老师");
// 从类中获取成员变量Ivar
Ivar ageIvar = class_getInstanceVariable([People class], "_age");
// 为成员变量赋值
object_setIvar(peopleInstance, ageIvar, @33);
// 调用 peopleInstance 对象中的 s 方法选择器对应的方法
// objc_msgSend(peopleInstance, s, @"大家好!");
((void (*)(id, SEL, id))objc_msgSend)(peopleInstance, s, @"大家好!!!");
// 当People类或者它的子类的实例还存在,则不能调用objc_disposeClassPair这个方法;因此这里要先销毁实例对象后才能销毁类;
peopleInstance = nil;
// 销毁类
objc_disposeClassPair([People class]);
}
// 动态添加方法的实现
void sayFunction1(id self, SEL _cmd, id some) {
Ivar ageIvar = class_getInstanceVariable([self class], "_age");
NSString *age = object_getIvar(self, ageIvar);
NSLog(@"%@岁的%@说: %@, %@", age,[self valueForKey:@"name"],some, NSStringFromSelector(_cmd));
}
获取属性, 成员变量 以及 方法
@implementation People
- (NSDictionary *)allProperties {
unsigned int count = 0;
// 获取类的所有属性, 如果没有属性count就为0
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableDictionary *resultDict = [@{} mutableCopy];
for (int i = 0; i < count; i++) {
// 获取属性的名称和值
const char *propertyName = property_getName(properties[i]);
NSString *name = [NSString stringWithUTF8String:propertyName];
id propertyValue = [self valueForKey:name];
if (propertyValue) {
resultDict[name] = propertyValue;
} else {
resultDict[name] = @"字典的key对应的value不能为nil哦!";
}
}
// 这里properties是一个数组指针, 我们需要使用free函数来释放内存
free(properties);
return resultDict;
}
- (NSDictionary *)allIvars {
unsigned int count = 0;
NSMutableDictionary *resultDict = [@{} mutableCopy];
// 获取类的所有成员变量ivar
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
const char *ivarName = ivar_getName(ivars[i]);
NSString *name = [NSString stringWithUTF8String:ivarName];
id ivarValue = [self valueForKey:name];
if (ivarValue) {
resultDict[name] = ivarValue;
} else {
resultDict[name] = @"字典的key对应的value不能为nil哦~";
}
}
free(ivars);
return resultDict;
}
- (NSDictionary *)allMethods {
unsigned int count = 0;
NSMutableDictionary *resultDict = [@{} mutableCopy];
Method *methods = class_copyMethodList([self class], &count);
for (int i = 0; i < count; i++) {
SEL methodSEL = method_getName(methods[i]);
const char *methodName = sel_getName(methodSEL);
NSString *name = [NSString stringWithUTF8String:methodName];
unsigned int arguments = method_getNumberOfArguments(methods[i]);
resultDict[name] = @(arguments - 2);
}
free(methods);
return resultDict;
}
@end
给类添加 属性 及 回调block
// 在People的分类中进行
typedef void(^CodingCallBack)();
@interface People (Associated)
@property (strong, nonatomic) NSNumber *associatedBust; // 胸围
@property (copy, nonatomic) CodingCallBack associatedCallBack; // 写代码
@end
@implementation People (Associated)
- (NSNumber *)associatedBust {
// 获取关联对象
return objc_getAssociatedObject(self, @selector(associatedBust));
}
- (void)setAssociatedBust:(NSNumber *)associatedBust {
// 设置关联对象
objc_setAssociatedObject(self, @selector(associatedBust), associatedBust, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CodingCallBack)associatedCallBack {
return objc_getAssociatedObject(self, @selector(associatedCallBack));
}
- (void)setAssociatedCallBack:(CodingCallBack)associatedCallBack {
objc_setAssociatedObject(self, @selector(associatedCallBack), associatedCallBack, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
序列化 及 反序列化
@interface People2 : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name; // 姓名
@property (nonatomic, strong) NSNumber *age; // 年龄
@property (nonatomic, copy) NSString *occupation; // 职业
@property (nonatomic, copy) NSString *nationality; // 国籍
@end
@implementation People2
// 反序列化数据
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
const char *ivarName = ivar_getName(ivars[i]);
NSString *name = [NSString stringWithUTF8String:ivarName];
id value = [coder decodeObjectForKey:name];
[self setValue:value forKey:name];
}
free(ivars);
}
return self;
}
// 序列化数据
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
const char *ivarName = ivar_getName(ivars[i]);
NSString *name = [NSString stringWithUTF8String:ivarName];
id ivarValue = [self valueForKey:name];
[aCoder encodeObject:ivarValue forKey:name];
}
free(ivars);
}
@end
Json 及 model 互转
@interface People2 : NSObject
@property (nonatomic, copy) NSString *name; // 姓名
@property (nonatomic, strong) NSNumber *age; // 年龄
@property (nonatomic, copy) NSString *occupation; // 职业
@property (nonatomic, copy) NSString *nationality; // 国籍
// 生成model
- (instancetype)initWithDictionary:(NSDictionary *)dictionary;
// 转换成字典
- (NSDictionary *)covertToDictionary;
@end
@implementation People2
- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
for (NSString *key in dictionary.allKeys) {
id value = dictionary[key];
SEL setter = [self propertySetterByKey:key];
if (setter) {
// objc_msgSend(self, setter, value);
((void(*)(id, SEL, id))objc_msgSend)(self, setter, value);
}
}
}
return self;
}
- (NSDictionary *)covertToDictionary {
unsigned int count = 0;
objc_property_t *properties = class_copyPropertyList([self class], &count);
if (count != 0) {
NSMutableDictionary *resultDict = [@{} mutableCopy];
for (int i = 0; i < count; i++) {
const char *propertyName = property_getName(properties[i]);
NSString *key = [NSString stringWithUTF8String:propertyName];
SEL getter = [self propertyGetterByKey:key];
if (getter) {
id value = ((id (*)(id, SEL))objc_msgSend)(self, getter);
if (value) {
resultDict[key] = value;
} else {
resultDict[key] = @"字典的key对应的value不能为nil哦!";
}
}
}
free(properties);
return resultDict;
}
free(properties);
return nil;
}
// --------- private method --------------------------------------
- (SEL)propertySetterByKey:(NSString *)key {
// set方法, 首字母大写
NSString *propertySetterName = [NSString stringWithFormat:@"set%@:", key.capitalizedString];
SEL setter = NSSelectorFromString(propertySetterName);
if ([self respondsToSelector:setter]) {
return setter;
}
return nil;
}
- (SEL)propertyGetterByKey:(NSString *)key {
SEL getter = NSSelectorFromString(key);
if ([self respondsToSelector:getter]) {
return getter;
}
return nil;
}
@end
动态转换方法实现
// 添加了方法声明, 但是没有实现该方法
@interface People : NSObject
- (void)sing;
@end
@implementation People
+ (BOOL)resolveInstanceMethod:(SEL)sel {
// 我们没有给People类声明sing方法, 这里我们动态添加方法
if ([NSStringFromSelector(sel) isEqualToString:@"sing"]) {
class_addMethod([self class], sel, (IMP)otherSing, "v@:");
return YES;
}
return [super resolveClassMethod:sel];
}
void otherSing(id self, SEL cmd) {
NSLog(@"%@ 唱歌啦~~",((People *)self).name);
}
@end
修改方法调用对象
// Bird 类中并没有名字为 sing 的方法, 这时可以在Bird类中 将对象修改成People
@interface Bird : NSObject
@property (copy, nonatomic) NSString *name;
@end
@implementation Bird
// 第一步:我们不动态添加方法,返回NO,进入第二步;
+ (BOOL)resolveInstanceMethod:(SEL)sel {
return NO;
}
// 第二部:我们不指定备选对象响应aSelector,进入第三步;
- (id)forwardingTargetForSelector:(SEL)aSelector {
return nil;
}
// 第三步:返回方法选择器,然后进入第四部;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
if ([NSStringFromSelector(aSelector) isEqualToString:@"sing"]) {
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
return [super methodSignatureForSelector:aSelector];
}
// 第四部:这步我们修改调用对象
- (void)forwardInvocation:(NSInvocation *)anInvocation {
// 我们改变调用对象为People
People *p = [[People alloc] init];
p.name = @"t1";
[p sing];
}
@end
修改调用的方法
@interface Bird : NSObject
@property (copy, nonatomic) NSString *name;
@end
@implementation Bird
// 第一步:我们不动态添加方法,返回NO,进入第二步;
+ (BOOL)resolveInstanceMethod:(SEL)sel {
return NO;
}
// 第二部:我们不指定备选对象响应aSelector,进入第三步;
- (id)forwardingTargetForSelector:(SEL)aSelector {
return nil;
}
// 第三步:返回方法选择器,然后进入第四部;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
if ([NSStringFromSelector(aSelector) isEqualToString:@"sing"]) {
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
return [super methodSignatureForSelector:aSelector];
}
// 第四部:这步我们修改调用方法
- (void)forwardInvocation:(NSInvocation *)anInvocation {
[anInvocation setSelector:@selector(dance)];
// 还要指定是哪个对象的方法
[anInvocation invokeWithTarget:self];
}
// 若forwardInvocation没有实现,则会调用此方法
- (void)doesNotRecognizeSelector:(SEL)aSelector {
NSLog(@"消息无法处理: %@", NSStringFromSelector(aSelector));
}
- (void)dance {
NSLog(@"跳舞!! come on!~");
}
@end