RunTime

Runtime, 一套比较底层的C语言的库,  是OC的底层实现

使用场景:

- 利用RunTimer,在程序运行的时候, 动态创建一个类

- 利用RunTimer,在程序运行的时候, 动态为某个类添加,修改属性 / 方法 

- 遍历一个类的属性, 方法, 成员变量

导入头文件  #import

typedef struct objc_method *Method;   //代表方法

typedef struct objc_ivar *Ivar; 代表成员变量 


1. 对象归档/接档

自定义对象归档必须遵守协议

- (instancetype)initWithCoder:(NSCoder*)coder

{

self= [superinit];

if(self) {

NSArray*array = [selfgetAllproperty];

for(NSString*propertyinarray) {

[selfsetValue:[coderdecodeObjectForKey:property]forKey:property];

}

//self.name = [coder decodeObjectForKey:@"name"];

//self.age = [[coder decodeObjectForKey:@"age"] intValue];

}

returnself;

}

- (void)encodeWithCoder:(NSCoder*)coder

{

//[coder encodeObject:self.name forKey:@"name"];

//[coder encodeObject:@(self.age) forKey:@"age"];

NSArray*array = [selfgetAllproperty];

for(NSString*propertyinarray) {

[coderencodeObject:[selfvalueForKey:property]forKey:property];

}

}

- (NSArray*)getAllproperty{

NSMutableArray*arr = [NSMutableArrayarray];

unsignedintcount =0;

objc_property_t*ivars =class_copyPropertyList([Personclass], &count);

for(inti =0; i

objc_property_tvar = ivars[i];

constchar*name =property_getName(var);

[arraddObject:[NSStringstringWithFormat:@"%s",name]];

}

returnarr;

}

Person*p = [[Personalloc]init];

p.name=@"eqefadv";

NSString*tempPath =NSTemporaryDirectory();

//存的是二进制,什么格式无所谓

NSString*fileP = [tempPathstringByAppendingPathComponent:@"xueshan.txt"];

//归档

[NSKeyedArchiver   archiveRootObject: ptoFile:fileP];

//解档

 Person*p = [NSKeyedUnarchiver  unarchiveObjectWithFile:fileP];

2. 方法欺骗

//改变方法指针的指向, 从而交换方法实现

//load方法在main方法之前调用

+ (void)load{

Methodm1 =class_getClassMethod([NSURLclass],@selector(URLWithString:));

Methodm2 =class_getClassMethod([NSURLclass],@selector(xs_URLWithString:));

method_exchangeImplementations(m1, m2);

}

+ (instancetype)xs_URLWithString:(NSString*)URLString{

NSURL*url = [NSURL    xs_URLWithString:URLString];

if(!url) {

NSLog(@"url为空的");

}

return url;

}


runtime的始终用法大全:       http://www.jianshu.com/p/3182646001d1

你可能感兴趣的:(RunTime)