iOS runtime(基礎篇)
iOS runtime(理論篇)
前面2篇介紹了runtime一些概念。接下來看看runtime在實際開發中都有哪些使用。
1.消息機制
Person *p = [[Person alloc] init];
// 調用對象方法
[p eat];
// 本質:讓對象發送消息
objc_msgSend(p, @selector(eat));
2.交換方法
當系統提供的方法需要擴展時,并且保留需要原有的系統功能,就聽到了交換方法了。
{
// 交換方法
// 獲取imageWithName方法地址
Method imageWithName = class_getClassMethod(self, @selector(imageWithName:));
// 獲取imageWithName方法地址
Method imageName = class_getClassMethod(self, @selector(imageNamed:));
// 交換方法地址,相當于交換實現方式 method_exchangeImplementations(imageWithName, imageName);
}
// 既能加載圖片又能打印
+ (instancetype)imageWithName:(NSString *)name {
// 這里調用imageWithName,相當于調用imageName
UIImage *image = [self imageWithName:name];
if (image == nil) {
NSLog(@"加載空的圖片");
}
return image;
}
3.動態添加方法
如果一個類方法非常多,加載了到內存的時候也比較耗費資源,需給每個方法生成映射表,可以使用動態給某個類,添加方法解決。
@implementation ViewController
- (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
@implementation Person
// void(*)() // 默認方法都有兩個隱式參數,
void eat(id self,SEL sel) {
NSLog(@"%@ %@",self,NSStringFromSelector(sel));
}
// 當一個對象調用未實現的方法,會調用這個方法處理,并且會把對應的方法列表傳過來.
// 剛好可以用來判斷,未實現的方法是不是我們想要動態添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if (sel == @selector(eat)) {
// 動態添加eat方法
// 第一個參數:給哪個類添加方法
// 第二個參數:添加方法的方法編號
// 第三個參數:添加方法的函數實現(函數地址)
// 第四個參數:函數的類型,(返回值+參數類型)
class_addMethod(self, @selector(eat), eat, "v@:");
}
return [super resolveInstanceMethod:sel];
}
@end
4.給類添加屬性
給一個類聲明屬性,其實本質就是給這個類添加關聯,并不是直接把這個值的內存空間添加到類上。
- (NSString *)name {
// 根據關聯的key,獲取關聯的值。
return objc_getAssociatedObject(self, key);
}
- (void)setName:(NSString *)name {
// 第一個參數:給哪個對象添加關聯
// 第二個參數:關聯的key,通過這個key獲取
// 第三個參數:關聯的value
// 第四個參數:關聯的策略
objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC); }
5.一些經典案例
1)字典轉模型
2)動態的歸檔解檔
過段時間整理下,分享一個完整的DEMO