Runtime 笔记

runtime 介绍

Objective-C 语言将决定尽可能的从编译和链接时推迟到运行时。只要有可能,Objective-C 总是使用动态 的方式来解决问题。这意味着 Objective-C 语言不仅需要一个编译器,同时也需要一个运行时系统来执行 编译好的代码。这儿的运行时系统扮演的角色类似于 Objective-C 语言的操作系统,Objective-C 基于该系统来工作。

runtime 了解

方法调用的本质,就是让对象发送消息。
objc_msgSend,只有对象才能发送消息,因此以objc开头.
使用消息机制前提,必须导入#import <objc/runtime.h>

消息机制简单使用
// 创建person对象
Person*p = [[Person alloc] init];
// 调用对象方法
[p eat];
// 本质:让对象发送消息
objc_msgSend(p, @selector(eat));
// 调用类方法的方式:两种
// 第一种通过类名调用
[Person eat];
// 第二种通过类对象调用
[[Person class]eat];
// 用类名调用类方法,底层会自动把类名转换成类对象调用
// 本质:让类对象发送消息
objc_msgSend([Personclass],@selector(eat));
三次拯救程序的机会
Method resolution
Fast forwarding
Normal forwarding

Method Resolution
首先,Objective-C 运行时会调用+resolveInstanceMethod:或者+resolveClassMethod:,让你有机会提供一个函数实现。如果你添加了函数并返回 YES, 那运行时系统就会重新启动一次消息发送的过程。还是以foo为例,你可以这么实现:

+ (BOOL)resolveInstanceMethod:(SEL)aSEL
{

if(aSEL ==@selector(foo:)){
class_addMethod([selfclass], aSEL, (IMP)fooMethod,"v@:");
returnYES;
}
return[superresolveInstanceMethod];
}

Core Data 有用到这个方法。NSManagedObjects 中 properties 的 getter 和 setter 就是在运行时动态添加的。
如果 resolve 方法返回 NO ,运行时就会移到下一步:消息转发(Message Forwarding)。
PS:iOS 4.3 加入很多新的 runtime 方法,主要都是以 imp 为前缀的方法,比如imp_implementationWithBlock()用 block 快速创建一个 imp 。
上面的例子可以重写成:

IMPfooIMP = imp_implementationWithBlock(^(id_self) {
NSLog(@"Doing foo");
});
class_addMethod([selfclass], aSEL, fooIMP,"v@:");

Fast forwarding
如果目标对象实现了-forwardingTargetForSelector:,Runtime 这时就会调用这个方法,给你把这个消息转发给其他对象的机会。

- (id)forwardingTargetForSelector:(SEL)aSelector
{
if(aSelector ==@selector(foo:)){
returnalternateObject;
}
return[superforwardingTargetForSelector:aSelector];
}

只要这个方法返回的不是 nil 和 self,整个消息发送的过程就会被重启,当然发送的对象会变成你返回的那个对象。否则,就会继续 Normal Fowarding 。
这里叫 Fast ,只是为了区别下一步的转发机制。因为这一步不会创建任何新的对象,但下一步转发会创建一个 NSInvocation 对象,所以相对更快点。
****Normal forwarding****
这一步是 Runtime 最后一次给你挽救的机会。首先它会发送-methodSignatureForSelector:消息获得函数的参数和返回值类型。如果-methodSignatureForSelector:返回 nil ,Runtime 则会发出-doesNotRecognizeSelector:消息,程序这时也就挂掉了。如果返回了一个函数签名,Runtime 就会创建一个 NSInvocation 对象并发送-forwardInvocation:消息给目标对象。
NSInvocation 实际上就是对一个消息的描述,包括selector 以及参数等信息。所以你可以在-forwardInvocation:里修改传进来的 NSInvocation 对象,然后发送-invokeWithTarget:消息给它,传进去一个新的目标:

- (void)forwardInvocation:(NSInvocation*)invocation
{
SELsel = invocation.selector;
if([alternateObject respondsToSelector:sel]) {
[invocation invokeWithTarget:alternateObject];
}
else{
[selfdoesNotRecognizeSelector:sel];
}
}

Cocoa 里很多地方都利用到了消息传递机制来对语言进行扩展,如 Proxies、NSUndoManager 跟 Responder Chain。NSProxy 就是专门用来作为代理转发消息的;NSUndoManager 截取一个消息之后再发送;而 Responder Chain 保证一个消息转发给合适的响应者。
Objective-C 中给一个对象发送消息会经过以下几个步骤:
在对象类的 dispatch table 中尝试找到该消息。如果找到了,跳到相应的函数IMP去执行实现代码;
如果没有找到,Runtime 会发送+resolveInstanceMethod:或者+resolveClassMethod:尝试去 resolve 这个消息;
如果 resolve 方法返回 NO,Runtime 就发送-forwardingTargetForSelector:允许你把这个消息转发给另一个对象;
如果没有新的目标对象返回, Runtime 就会发送-methodSignatureForSelector:和-forwardInvocation:消息。你可以发送-invokeWithTarget:消息来手动转发消息或者发送-doesNotRecognizeSelector:抛出异常。
runtime 方法运用
person 类为例

@interfacePerson:NSObject
{
NSString*address;
}
@property(nonatomic,strong)NSString*name;
@property(nonatomic,assign)NSIntegerage;
//遍历一个person类的所有的成员变量IvarList
- (void) getAllIvarList {
unsignedintmethodCount =0;
Ivar * ivars = class_copyIvarList([Personclass], &methodCount);
for(unsignedinti =0; i < methodCount; i ++) {
Ivar ivar = ivars[i];
constchar* name = ivar_getName(ivar);
constchar* type = ivar_getTypeEncoding(ivar);
NSLog(@"Person拥有的成员变量的类型为%s,名字为 %s ",type, name);
}
free(ivars);
}
2016-06-1520:26:39.412demo-Cocoa之method swizzle[17798:2565569] Person拥有的成员变量的类型为@"NSString",名字为 address
2016-06-1520:26:39.413demo-Cocoa之method swizzle[17798:2565569] Person拥有的成员变量的类型为@"NSString",名字为 _name
2016-06-1520:26:39.413demo-Cocoa之method swizzle[17798:2565569] Person拥有的成员变量的类型为q,名字为 _age
//遍历获取所有属性Property
- (void) getAllProperty {
unsignedintpropertyCount =0;
objc_property_t*propertyList = class_copyPropertyList([Personclass], &propertyCount);
for(unsignedinti =0; i < propertyCount; i++ ) {
objc_property_t*thisProperty = propertyList[i];
constchar* propertyName = property_getName(*thisProperty);
NSLog(@"Person拥有的属性为: '%s'", propertyName);
}
}
2016-06-15 20:25:19.653 demo-Cocoa之method swizzle[17778:2564081] Person拥有的属性为: 'name'
2016-06-15 20:25:19.653 demo-Cocoa之method swizzle[17778:2564081] Person拥有的属性为: 'age'

访问私有变量
我们知道,OC中没有真正意义上的私有变量和方法,要让成员变量私有,要放在m文件中声明,不对外暴露。如果我们知道这个成员变量的名称,可以通过runtime获取成员变量,再通过getIvar来获取它的值。

Ivar ivar = class_getInstanceVariable([Model class],"_str1");
NSString * str1 = object_getIvar(model, ivar);

runtime学习阶段 (可以通过这个例子实现 one-to-N的delegates)
1.调用一个函数,但是函数没有实现

- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(doSomething)];
}

不出意外,程序崩溃

reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680'**
***** First throw call stack:**

2.实现+ (BOOL)resolveInstanceMethod:(SEL)sel,依旧崩溃
因为没有找到doSomething这个方法,下面我们在里面实现+ (BOOL)resolveInstanceMethod:(SEL)sel这个方法,并且判断如果SEL是doSomething那就输出add method here

- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(doSomething)];
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if(sel ==@selector(doSomething)) {
NSLog(@"add method here");
returnYES;
}
return[super resolveInstanceMethod:sel];
}

继续运行, NSLog

**2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] add method here**
**2015-12-24 10:47:24.687 RuntimeTest1[2007:382077] -[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0**
**2015-12-24 10:47:24.690 RuntimeTest1[2007:382077] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7f9568c331f0'**
***** First throw call stack:**

3.通过class_addMethod添加方法
可以看到程序依然是崩溃了,但是我们可以看到输出了add method here,这说明我们+ (BOOL)resolveInstanceMethod:(SEL)sel这个方法执行了,并进入了判断,所以,在这儿,我们可以做一下操作,使这个方法得到响应,不至于走到最后
- (void)doesNotRecognizeSelector:(SEL)aSelector这个方法中而崩掉了,接下来,我们继续操作,如下

- (void)viewDidLoad {
    [super viewDidLoad];
    [self performSelector:@selector(doSomething)];
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if(sel ==@selector(doSomething)) {
        NSLog(@"add method here");        
        class_addMethod([selfclass], sel, (IMP)dynamicMethodIMP,"v@:");
        returnYES;
    }
    return [superresolveInstanceMethod:sel];
}
void dynamicMethodIMP (idself, SEL _cmd) {
    NSLog(@"doSomething SEL");
}


导入了并且在+ (BOOL)resolveInstanceMethod:(SEL)sel中执行了class_addMethod这个方法,然后定义了一个void dynamicMethodIMP (id self, SEL _cmd)这个函数,运行工程,看log

**2015-12-2411:45:11.934RuntimeTest1[2284:478571] add method here**
**2015-12-2411:45:11.934RuntimeTest1[2284:478571] doSomething SEL**

这时候我们发现,程序并没有崩溃,而且还输出了doSomething SEL
这时候就说明我们已经通过runtime成功的向我们这个类中添加了一个方法。
关于class_addMethod这个方法的定义
OBJC_EXPORTBOOLclass_addMethod(Class cls, SEL name, IMP imp,constchar*types)
cls在这个类中添加方法,也就是需要添加方法的类
name方法名
imp本质上就是一个函数指针,指向方法的实现
types定义该数返回值类型和参数类型的字符串,这里比如"v@:",其中v就是void,带表返回类型就是空,@代表参数,这里指的是id(self),这里:指的是方法SEL(_cmd),比如我再定义一个函数

int newMethod (idself, SEL _cmd,NSString*str) {
return100;
}

那么添加这个函数的方法就应该是
ass_addMethod([self class], @selector(newMethod), (IMP)newMethod, "i@:@");
4.如果在+ (BOOL)resolveInstanceMethod:(SEL)sel中没有找到或者添加方法
那么,消息继续往下传递到- (id)forwardingTargetForSelector:(SEL)aSelector
重新建个工程,然后增加一个叫SecondViewController的类,里面添加一个- (void)secondVCMethod方法,如下
在SecondViewController中

@implementationSecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)secondVCMethod {
NSLog(@"This is secondVC method !");
}

目录结构:
在ViewController中

@implementationViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(secondVCMethod)];
}

运行结果,崩溃

reason: '-[ViewController secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10'**

5.在ViewController中实现 forwardingTargetForSelector:(SEL)aSelector 方法后,解决崩溃

@implementationViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(secondMethod)];
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
//先得到第二个控制器的类
Class class =NSClassFromString(@"SecondViewController");
//创建新的控制器
UIViewController*VC = [classnew];
//如果方法名相同,就实现方法
if(aSelector ==NSSelectorFromString(@"secondMethod")) {
NSLog(@"secondMethod will do it");
returnVC;
}
returnnil;
}
+ (BOOL)resolveInstanceMethod:(SEL)sel{
return[superresolveInstanceMethod:sel];
}

运行结果

**2015-12-2414:00:34.168RuntimeTest2[3284:870957] secondVCdothis!**
**2015-12-2414:00:34.169RuntimeTest2[3284:870957] This is secondVC method !**

解释:

- (id)forwardingTargetForSelector:(SEL)aSelector {
Class class =NSClassFromString(@"SecondViewController");
UIViewController*vc = class.new;
if(aSelector ==NSSelectorFromString(@"secondVCMethod")) {
NSLog(@"secondVC do this !");
returnvc;
}
returnnil;
}

在没有找到- (void)secondVCMethod这个方法的时候,消息继续传递,直到- (id)forwardingTargetForSelector:(SEL)aSelector,然后我在里面创建了一个SecondViewController的对象,并且判断如果有这个方法,就返回SecondViewController的对象。这个函数就是消息的转发,在这儿我们成功的把消息传给了SecondViewController,然后让它来执行,所以就执行了那个方法。同时,也相当于完成了一个多继承!
可以通过message forwarding 去实现 one-to-N的delegates
runtime的使用场景
1.字典转模型
篇幅一:

NSDictionary*dict =@{@"name":@"itcast",@"age":@18,@"height":@1.7};
unsignedintcount =0;
Ivar*Ivars =class_copyIvarList([CZPersonclass], &count);
CZPerson*person = [CZPersonnew];
for(inti =0; i < count; ++i) {
Ivarvar = Ivars[i];
constchar*str =ivar_getName(var);
NSMutableString*strName = [NSMutableStringstringWithString:[NSStringstringWithUTF8String:str]];
NSString*name =  [strNamesubstringFromIndex:1];
[personsetValue:dict[name]forKey:name];
}
NSLog(@"%@ %d %f",person.name,person.age,person.height);

篇幅二: 小马哥
思路:利用运行时,遍历模型中所有属性,根据模型的属性名,去字典中查找key,取出对应的值,给模型的属性赋值。
步骤:提供一个NSObject分类,专门字典转模型,以后所有模型都可以通过这个分类转。

@implementationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 解析Plist文件
NSString*filePath = [[NSBundlemainBundle] pathForResource:@"status.plist"ofType:nil];
NSDictionary*statusDict = [NSDictionarydictionaryWithContentsOfFile:filePath];
// 获取字典数组
NSArray*dictArr = statusDict[@"statuses"];
// 自动生成模型的属性字符串
//    [NSObject resolveDict:dictArr[0][@"user"]];
_statuses = [NSMutableArrayarray];
// 遍历字典数组
for(NSDictionary*dictindictArr) {
Status *status = [Status modelWithDict:dict];
[_statuses addObject:status];
}
// 测试数据
NSLog(@"%@ %@",_statuses,[_statuses[0] user]);
}
@end
@implementationNSObject(Model)
+ (instancetype)modelWithDict:(NSDictionary*)dict
{
// 思路:遍历模型中所有属性-》使用运行时
// 0.创建对应的对象
idobjc = [[selfalloc] 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];
*/
unsignedintcount;
// 获取类中的所有成员属性
Ivar *ivarList = class_copyIvarList(self, &count);
for(inti =0; i < count; i++) {
// 根据角标,从数组取出对应的成员属性
Ivar ivar = ivarList[i];
// 获取成员属性名
NSString*name = [NSStringstringWithUTF8String:ivar_getName(ivar)];
// 处理成员属性名->字典中的key
// 从第一个角标开始截取
NSString*key = [name substringFromIndex:1];
// 根据成员属性名去字典中查找对应的value
idvalue = dict[key];
// 二级转换:如果字典中还有字典,也需要把对应的字典转换成模型
// 判断下value是否是字典
if([value isKindOfClass:[NSDictionaryclass]]) {
// 字典转模型
// 获取模型的类对象,调用modelWithDict
// 模型的类名已知,就是成员属性的类型
// 获取成员属性类型
NSString*type = [NSStringstringWithUTF8String:ivar_getTypeEncoding(ivar)];
// 生成的是这种@"@\"User\"" 类型 -》 @"User"  在OC字符串中 \" -> ",\是转义的意思,不占用字符
// 裁剪类型字符串
NSRangerange = [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:[NSArrayclass]]) {
// 判断对应类有没有实现字典数组转模型数组的协议
if([selfrespondsToSelector:@selector(arrayContainModelClass)]) {
// 转换成id类型,就能调用任何对象的方法
ididSelf =self;
// 获取数组中字典对应的模型
NSString*type =  [idSelf arrayContainModelClass][key];
// 生成模型
Class classModel =NSClassFromString(type);
NSMutableArray*arrM = [NSMutableArrayarray];
// 遍历字典数组,生成模型数组
for(NSDictionary*dictinvalue) {
// 字典转模型
idmodel =  [classModel modelWithDict:dict];
[arrM addObject:model];
}
// 把模型数组赋值给value
value = arrM;
}
}
if(value) {// 有值,才需要给模型的属性赋值
// 利用KVC给模型中的属性赋值
[objc setValue:value forKey:key];
}
}
returnobjc;
}
@end

2.归档解档
篇幅一:

//归档
- (void)encodeWithCoder:(NSCoder*)enCoder{
//取得所有成员变量名
NSArray*properNames = [[selfclass] propertyOfSelf];
for(NSString*propertyNameinproperNames) {
//创建指向get方法
SELgetSel =NSSelectorFromString(propertyName);
//对每一个属性实现归档
[enCoderencodeObject:[selfperformSelector:getSel]forKey:propertyName];
}
}
//解档
- (id)initWithCoder:(NSCoder*)aDecoder{
//取得所有成员变量名
NSArray*properNames = [[selfclass] propertyOfSelf];
for(NSString*propertyNameinproperNames) {
//创建指向属性的set方法
// 1.获取属性名的第一个字符,变为大写字母
NSString*firstCharater = [propertyNamesubstringToIndex:1].uppercaseString;
// 2.替换掉属性名的第一个字符为大写字符,并拼接出set方法的方法名
NSString*setPropertyName = [NSStringstringWithFormat:@"set%@%@:",firstCharater,[propertyNamesubstringFromIndex:1]];
SELsetSel =NSSelectorFromString(setPropertyName);
[selfperformSelector:setSelwithObject:[aDecoderdecodeObjectForKey:propertyName]];
}
returnself;
}

篇幅二:
原理描述:用runtime提供的函数遍历Model自身所有属性,并对属性进行encode和decode操作。
核心方法:在Model的基类中重写方法:

- (void)encodeWithCoder:(NSCoder*)aCoder {
unsignedintoutCount;
Ivar * ivars = class_copyIvarList([selfclass], &outCount);
for(inti =0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString* key = [NSStringstringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[selfvalueForKey:key] forKey:key];
}
}
- (id)initWithCoder:(NSCoder*)aDecoder {
if(self= [superinit]) {
unsignedintoutCount;
Ivar * ivars = class_copyIvarList([selfclass], &outCount);
for(inti =0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString* key = [NSStringstringWithUTF8String:ivar_getName(ivar)];
[selfsetValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
returnself;
}

3.runtime交换方法
开发使用场景:系统自带的方法功能不够,给系统自带的方法扩展一些功能,并且保持原有的功能。
方式一:继承系统的类,重写方法.
方式二:使用runtime,交换方法.

@implementationViewController
- (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 = [UIImageimageNamed:@"123"];
}
@end
@implementationUIImage(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 = [selfimageWithName:name];
if(image == nil) {
NSLog(@"加载空的图片");
}
returnimage;
}
@end

4.动态添加方法 (可以用于 “代理”)
开发使用场景:如果一个类方法非常多,加载类到内存的时候也比较耗费资源,需要给每个方法生成映射表,可以使用动态给某个类,添加方法解决。
经典面试题:有没有使用performSelector,其实主要想问你有没有动态添加过方法。
简单使用

@implementationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *p = [[Person alloc] init];
// 默认person,没有实现eat方法,可以通过performSelector调用,但是会报错。
// 动态添加方法就不会报错
[p performSelector:@selector(eat)];
}
@end
@implementationPerson
// void(*)()
// 默认方法都有两个隐式参数,
voideat(idself,SEL sel)
{
NSLog(@"%@ %@",self,NSStringFromSelector(sel));
}
// 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来.
// 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if(sel ==@selector(eat)) {
// 动态添加eat方法
// 第一个参数:给哪个类添加方法
// 第二个参数:添加方法的方法编号
// 第三个参数:添加方法的函数实现(函数地址)
// 第四个参数:函数的类型,(返回值+参数类型) v:void @:对象->self :表示SEL->_cmd
class_addMethod(self,@selector(eat), eat,"v@:");
}
return[superresolveInstanceMethod:sel];
}
@end

5.动态添加属性
原理:给一个类声明属性,其实本质就是给这个类添加关联,并不是直接把这个值的内存空间添加到类存空间。

@implementationViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 给系统NSObject类动态添加属性name
NSObject*objc = [[NSObjectalloc] init];
objc.name=@"小码哥";
NSLog(@"%@",objc.name);
}
@end
// 定义关联的key
staticconstchar*key ="name";
@implementationNSObject(Property)
- (NSString*)name
{
// 根据关联的key,获取关联的值。
returnobjc_getAssociatedObject(self, key);
}
- (void)setName:(NSString*)name
{
// 第一个参数:给哪个对象添加关联
// 第二个参数:关联的key,通过这个key获取
// 第三个参数:关联的value
// 第四个参数:关联的策略
objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

6.Json到Model的转化
原理描述:用runtime提供的函数遍历Model自身所有属性,如果属性在json中有对应的值,则将其赋值。
核心方法:在NSObject的分类中添加方法:

- (instancetype)initWithDict:(NSDictionary*)dict {
if(self= [selfinit]) {
//(1)获取类的属性及属性对应的类型
NSMutableArray* keys = [NSMutableArrayarray];
NSMutableArray* attributes = [NSMutableArrayarray];
/*
* 例子
* name = value3 attribute = T@"NSString",C,N,V_value3
* name = value4 attribute = T^i,N,V_value4
*/
unsignedintoutCount;
objc_property_t * properties = class_copyPropertyList([selfclass], &outCount);
for(inti =0; i < outCount; i ++) {
objc_property_t property = properties[i];
//通过property_getName函数获得属性的名字
NSString* propertyName = [NSStringstringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通过property_getAttributes函数可以获得属性的名字和@encode编码
NSString* propertyAttribute = [NSStringstringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即释放properties指向的内存
free(properties);
//(2)根据类型给属性赋值
for(NSString* keyinkeys) {
if([dict valueForKey:key] == nil)
continue;
[self set Value:[dict valueForKey:key] forKey:key];
}
}
return self;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,678评论 0 9
  • OC是一门动态语言,它将很多静态语言在编译和链接时期做的事情推迟到了运行时来处理,这就意味着它不仅需要一个编译器,...
    zziazm阅读 204评论 0 0
  • 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的...
    西木阅读 30,529评论 33 466
  • 我们常常会听说 Objective-C 是一门动态语言,那么这个「动态」表现在哪呢?我想最主要的表现就是 Obje...
    Ethan_Struggle阅读 2,162评论 0 7
  • 我们部门要招聘一个新人,挂和我一样的title,分担我的工作。 刚进公司的时候这个部门只有我一个人,靠着大小bos...
    绵绵piu阅读 396评论 3 1