运行时机制
,也就是在运行时候的一些机制,其中最主要的是消息机制。(运行时机制,就是运行时作一些事情,消息机制,就是方法的调用... )函数的调用在编译的时候会决定调用哪一个函数
。动态调用过程
,在编译的时候并不能决定真正调用哪一个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用。调用任何函数
,即便这个函数并未实现,只要声明过就不会报错。未实现的函数
就会报错。
使用运行时步骤
1.导入#import <objc/message.h>
2.谁的事情,谁开头
runtime的消息机制函数,在xcode6以后就没有提示参数
怎么才能让消息机制函数有参数提示?
点击工程文件-> build Setting ->搜索msg ->不要严肃检查消息机制调用面试
消息机制
前提,必须导入#import <objc/message.h>
// 建立person对象 Person *p = [[Person alloc] init]; // 调用对象方法 [p eat]; // 本质:让对象发送消息 objc_msgSend(p, @selector(eat)); SEL:方法编号 -> 寻找方法 // 调用类方法的方式:两种 // 第一种经过类名调用 [Person eat]; // 第二种经过类对象调用( 类方法调用本质:不是拿到类名调用,本质是拿到类对象) [[Person class] eat]; // 用类名调用类方法,底层会自动把类名转换成类对象调用 // 本质:让类对象发送消息 objc_msgSend([Person class], @selector(eat));
消息机制原理:对象根据方法编号SEL去映射表查找对应的方法实现数组
调用流程:
// 1.首先获取p对象的isa指针,就去isa指向类中查找
// 2.根据传入SEL找到对应方法名(函数入口)(这些方法实际上会转换为函数)
// 3.直接调用函数实现xcode
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 需求:给imageNamed方法提供功能,每次加载图片就判断下图片是否加载成功。 // 步骤一:先搞个分类,定义一个能加载图片而且能打印的方法+ (instancetype)imageWithName:(NSString *)name; // 步骤二:交换imageNamed和imageWithName的实现,就能调用imageWithName,间接调用imageWithName的实现。 UIImage *image = [UIImage imageNamed:@"ljw"]; } @end @implementation UIImage (Image) // 加载分类到内存的时候调用 + (void)load { // 交换方法 // 获取imageWithName方法地址 Method imageWithName = class_getClassMethod(self, @selector(imageWithName:)); // 获取imageWithName方法地址 Method imageName = class_getClassMethod(self, @selector(imageNamed:)); // 交换方法地址,至关于交换实现方式 method_exchangeImplementations(imageWithName, imageName); } // 不能在分类中重写系统方法imageNamed,由于会把系统的功能给覆盖掉,并且分类中不能调用super. // 既能加载图片又能打印 + (instancetype)imageWithName:(NSString *)name { // 这里调用imageWithName,至关于调用imageName UIImage *image = [self imageWithName:name]; if (image == nil) { NSLog(@"加载空图片"); } return image; } @end
交换以前: app
交换以后: 函数
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 给系统NSObject类动态添加属性 name NSObject *objc = [[NSObject alloc] init]; objc.name = @"LJW"; NSLog(@"%@",objc.name); } @end // 定义关联的key static const char *key = "name"; @implementation NSObject (Property) - (NSString *)name { // 根据关联的key,获取关联的值。 return objc_getAssociatedObject(self, key); } - (void)setName:(NSString *)name { // 第一个参数:给哪一个对象添加关联 // 第二个参数:关联的key,经过这个key获取(属性名) // 第三个参数:关联的value // 第四个参数:关联的策略 (strong) objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end
自动生成属性代码测试
@implementation NSDictionary (Code) - (void)createPropertyCode { // 根据字典中的key去生成对应属性 // 模型中属性名 就是 key NSMutableString *codes = [NSMutableString string]; // 遍历字典 [self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) { NSString *code; // 生成一行属性代码 if ([value isKindOfClass:[NSString class]]) { code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key]; } else if ([value isKindOfClass:[NSArray class]]) { code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key]; } else if ([value isKindOfClass:[NSDictionary class]]) { code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key]; } else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) { code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key]; } else if ([value isKindOfClass:[NSNumber class]]) { code = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;",key]; } // 拼接属性代码 [codes appendFormat:@"\n%@\n",code]; }]; NSLog(@"%@",codes); } @end
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.' // 获取文件全路径 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil]; // 解析plist文件,生成字典对象 NSDictionary *statusDict = [NSDictionary dictionaryWithContentsOfFile:filePath]; // 设计模型,定义属性 // [statusDict createPropertyCode]; // 字典转模型 StatusItem *item = [StatusItem statusWithDict:statusDict]; NSLog(@"%@",item); }
[<Status 0x7fa74b545d60> setValue:forUndefinedKey:]
报key
找不到的错。setValue:forUndefinedKey:
报错。setValue:forUndefinedKey:
,把系统的方法覆盖, 就能继续使用KVC,字典转模型了。- (void)setValue:(id)value forUndefinedKey:(NSString *)key { }
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 解析Plist文件 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil]; NSDictionary *statusDict = [NSDictionary dictionaryWithContentsOfFile:filePath]; // 获取字典数组 NSArray *dictArr = statusDict[@"statuses"]; // 自动生成模型的属性字符串 // [NSObject resolveDict:dictArr[0][@"user"]]; _statuses = [NSMutableArray array]; // 遍历字典数组 for (NSDictionary *dict in dictArr) { Status *status = [Status modelWithDict:dict]; [_statuses addObject:status]; } // 测试数据 NSLog(@"%@ %@",_statuses,[_statuses[0] user]); } @end @implementation NSObject (Model) + (instancetype)modelWithDict:(NSDictionary *)dict { // 思路:遍历模型中全部属性-》使用运行时 // 0.建立对应的对象 id objc = [[self alloc] init]; // 1.利用runtime给对象中的成员属性赋值 // class_copyIvarList:获取类中的全部成员属性 // Ivar:成员属性的意思 // 第一个参数:表示获取哪一个类中的成员属性 // 第二个参数:表示这个类有多少成员属性,传入一个Int变量地址,会自动给这个变量赋值 // 返回值Ivar *:指的是一个ivar数组,会把全部成员属性放在一个数组中,经过返回的数组就能所有获取到。 /* 相似下面这种写法 Ivar ivar; Ivar ivar1; Ivar ivar2; // 定义一个ivar的数组a Ivar a[] = {ivar,ivar1,ivar2}; // 用一个Ivar *指针指向数组第一个元素 Ivar *ivarList = a; // 根据指针访问数组第一个元素 ivarList[0]; */ unsigned int count; // 获取类中的全部成员属性 Ivar *ivarList = class_copyIvarList(self, &count); for (int i = 0; i < count; i++) { // 根据角标,从数组取出对应的成员属性 Ivar ivar = ivarList[i]; // 获取成员属性名 NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)]; // 处理成员属性名->字典中的key // 从第一个角标开始截取 NSString *key = [name substringFromIndex:1]; // 根据成员属性名去字典中查找对应的value id value = dict[key]; // 二级转换:若是字典中还有字典,也须要把对应的字典转换成模型 // 判断下value是不是字典 if ([value isKindOfClass:[NSDictionary class]]) { // 字典转模型 // 获取模型的类对象,调用modelWithDict // 模型的类名已知,就是成员属性的类型 // 获取成员属性类型 NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)]; // 生成的是这种@"@\"User\"" 类型 -》 @"User" 在OC字符串中 \" -> ",\是转义的意思,不占用字符 // 裁剪类型字符串 NSRange range = [type rangeOfString:@"\""]; type = [type substringFromIndex:range.location + range.length]; range = [type rangeOfString:@"\""]; // 裁剪到哪一个角标,不包括当前角标 type = [type substringToIndex:range.location]; // 根据字符串类名生成类对象 Class modelClass = NSClassFromString(type); if (modelClass) { // 有对应的模型才须要转 // 把字典转模型 value = [modelClass modelWithDict:value]; } } // 三级转换:NSArray中也是字典,把数组中的字典转换成模型. // 判断值是不是数组 if ([value isKindOfClass:[NSArray class]]) { // 判断对应类有没有实现字典数组转模型数组的协议 if ([self respondsToSelector:@selector(arrayContainModelClass)]) { // 转换成id类型,就能调用任何对象的方法 id idSelf = self; // 获取数组中字典对应的模型 NSString *type = [idSelf arrayContainModelClass][key]; // 生成模型 Class classModel = NSClassFromString(type); NSMutableArray *arrM = [NSMutableArray array]; // 遍历字典数组,生成模型数组 for (NSDictionary *dict in value) { // 字典转模型 id model = [classModel modelWithDict:dict]; [arrM addObject:model]; } // 把模型数组赋值给value value = arrM; } } if (value) { // 有值,才须要给模型的属性赋值 // 利用KVC给模型中的属性赋值 [objc setValue:value forKey:key]; } } return objc; } @end
写在最后,runtime在开发中十分强大,是开发中的'黑魔法'ui
每每作到不少好用的功能,很强大!!!atom