runtime 介紹
Objective-C 語言將決定盡可能的從編譯和鏈接時推遲到運行時。只要有可能,Objective-C 總是使用動態(tài) 的方式來解決問題。這意味著 Objective-C 語言不僅需要一個編譯器,同時也需要一個運行時系統(tǒng)來執(zhí)行 編譯好的代碼。這兒的運行時系統(tǒng)扮演的角色類似于 Objective-C 語言的操作系統(tǒng),Objective-C 基于該系統(tǒng)來工作。在自己印象筆記中,重新整理了這篇文章,作為個人學習、理解市埋、備用和分享.
runtime 了解
- 方法調(diào)用的本質(zhì),就是讓對象發(fā)送消息恕刘。
- objc_msgSend,只有對象才能發(fā)送消息缤谎,因此以objc開頭.
- 使用消息機制前提,必須導入#import <objc/message.h>
- 消息機制簡單使用
// 創(chuàng)建person對象
Person *p = [[Person alloc] init];
// 調(diào)用對象方法
[p eat];
// 本質(zhì):讓對象發(fā)送消息
objc_msgSend(p, @selector(eat));
// 調(diào)用類方法的方式:兩種
// 第一種通過類名調(diào)用
[Person eat];
// 第二種通過類對象調(diào)用
[[Person class] eat];
// 用類名調(diào)用類方法褐着,底層會自動把類名轉(zhuǎn)換成類對象調(diào)用
// 本質(zhì):讓類對象發(fā)送消息
objc_msgSend([Person class], @selector(eat));
三次拯救程序的機會
- Method resolution
- Fast forwarding
- Normal forwarding
Method Resolution
首先坷澡,Objective-C 運行時會調(diào)用 +resolveInstanceMethod: 或者 +resolveClassMethod:,讓你有機會提供一個函數(shù)實現(xiàn)含蓉。如果你添加了函數(shù)并返回 YES频敛, 那運行時系統(tǒng)就會重新啟動一次消息發(fā)送的過程项郊。還是以 foo 為例,你可以這么實現(xiàn):
+ (BOOL)resolveInstanceMethod:(SEL)aSEL
{
if(aSEL == @selector(foo:)){
class_addMethod([self class], aSEL, (IMP)fooMethod, "v@:");
return YES;
}
return [super resolveInstanceMethod];
}
Core Data 有用到這個方法斟赚。NSManagedObjects 中 properties 的 getter 和 setter 就是在運行時動態(tài)添加的着降。
如果 resolve 方法返回 NO ,運行時就會移到下一步:消息轉(zhuǎn)發(fā)(Message Forwarding)拗军。
PS:iOS 4.3 加入很多新的 runtime 方法任洞,主要都是以 imp 為前綴的方法,比如 imp_implementationWithBlock() 用 block 快速創(chuàng)建一個 imp 发侵。
上面的例子可以重寫成:
IMP fooIMP = imp_implementationWithBlock(^(id _self) {
NSLog(@"Doing foo");
});
class_addMethod([self class], aSEL, fooIMP, "v@:");
Fast forwarding
如果目標對象實現(xiàn)了 -forwardingTargetForSelector: 交掏,Runtime 這時就會調(diào)用這個方法,給你把這個消息轉(zhuǎn)發(fā)給其他對象的機會刃鳄。
- (id)forwardingTargetForSelector:(SEL)aSelector
{
if(aSelector == @selector(foo:)){
return alternateObject;
}
return [super forwardingTargetForSelector:aSelector];
}
只要這個方法返回的不是 nil 和 self盅弛,整個消息發(fā)送的過程就會被重啟,當然發(fā)送的對象會變成你返回的那個對象叔锐。否則熊尉,就會繼續(xù) Normal Fowarding 。
這里叫 Fast 掌腰,只是為了區(qū)別下一步的轉(zhuǎn)發(fā)機制。因為這一步不會創(chuàng)建任何新的對象张吉,但下一步轉(zhuǎn)發(fā)會創(chuàng)建一個 NSInvocation 對象齿梁,所以相對更快點。
Normal forwarding
這一步是 Runtime 最后一次給你挽救的機會肮蛹。首先它會發(fā)送 -methodSignatureForSelector: 消息獲得函數(shù)的參數(shù)和返回值類型勺择。如果 -methodSignatureForSelector: 返回 nil ,Runtime 則會發(fā)出 -doesNotRecognizeSelector: 消息伦忠,程序這時也就掛掉了省核。如果返回了一個函數(shù)簽名,Runtime 就會創(chuàng)建一個 NSInvocation 對象并發(fā)送 -forwardInvocation: 消息給目標對象昆码。
NSInvocation 實際上就是對一個消息的描述气忠,包括selector 以及參數(shù)等信息。所以你可以在 -forwardInvocation: 里修改傳進來的 NSInvocation 對象赋咽,然后發(fā)送 -invokeWithTarget: 消息給它旧噪,傳進去一個新的目標:
- (void)forwardInvocation:(NSInvocation *)invocation
{
SEL sel = invocation.selector;
if([alternateObject respondsToSelector:sel]) {
[invocation invokeWithTarget:alternateObject];
}
else {
[self doesNotRecognizeSelector:sel];
}
}
Cocoa 里很多地方都利用到了消息傳遞機制來對語言進行擴展,如 Proxies脓匿、NSUndoManager 跟 Responder Chain淘钟。NSProxy 就是專門用來作為代理轉(zhuǎn)發(fā)消息的;NSUndoManager 截取一個消息之后再發(fā)送陪毡;而 Responder Chain 保證一個消息轉(zhuǎn)發(fā)給合適的響應者米母。
Objective-C 中給一個對象發(fā)送消息會經(jīng)過以下幾個步驟:
- 在對象類的 dispatch table 中嘗試找到該消息勾扭。如果找到了,跳到相應的函數(shù)IMP去執(zhí)行實現(xiàn)代碼铁瞒;
- 如果沒有找到妙色,Runtime 會發(fā)送 +resolveInstanceMethod: 或者 +resolveClassMethod: 嘗試去 resolve 這個消息;
- 如果 resolve 方法返回 NO精拟,Runtime 就發(fā)送 -forwardingTargetForSelector: 允許你把這個消息轉(zhuǎn)發(fā)給另一個對象燎斩;
- 如果沒有新的目標對象返回, Runtime 就會發(fā)送 -methodSignatureForSelector: 和 -forwardInvocation: 消息蜂绎。你可以發(fā)送 -invokeWithTarget: 消息來手動轉(zhuǎn)發(fā)消息或者發(fā)送 -doesNotRecognizeSelector: 拋出異常栅表。
runtime 方法運用
person 類為例
<!--Person.h文件-->
@interface Person : NSObject
{
NSString *address;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)NSInteger age;
//遍歷一個person類的所有的成員變量IvarList
- (void) getAllIvarList {
unsigned int methodCount = 0;
Ivar * ivars = class_copyIvarList([Person class], &methodCount);
for (unsigned int i = 0; i < methodCount; i ++) {
Ivar ivar = ivars[i];
const char * name = ivar_getName(ivar);
const char * type = ivar_getTypeEncoding(ivar);
NSLog(@"Person擁有的成員變量的類型為%s,名字為 %s ",type, name);
}
free(ivars);
}
<!--打印結果-->
2016-06-15 20:26:39.412 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類型為@"NSString"师枣,名字為 address
2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類型為@"NSString"怪瓶,名字為 _name
2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person擁有的成員變量的類型為q,名字為 _age
//遍歷獲取所有屬性Property
- (void) getAllProperty {
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([Person class], &propertyCount);
for (unsigned int i = 0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList[i];
const char* 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學習階段 (可以通過這個例子實現(xiàn) one-to-N的delegates)
1.調(diào)用一個函數(shù),但是函數(shù)沒有實現(xiàn)
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(doSomething)];
}
不出意外,程序崩潰
reason: '-[ViewController doSomething]: unrecognized selector sent to instance 0x7fe9f3736680'**
***** First throw call stack:**
2.實現(xiàn) + (BOOL)resolveInstanceMethod:(SEL)sel, 依舊崩潰
因為沒有找到doSomething這個方法杂曲,下面我們在里面實現(xiàn) + (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];
}
繼續(xù)運行, 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這個方法執(zhí)行了咱揍,并進入了判斷,所以棚饵,在這兒煤裙,我們可以做一下操作,使這個方法得到響應噪漾,不至于走到最后
- (void)doesNotRecognizeSelector:(SEL)aSelector這個方法中而崩掉了积暖,接下來,我們繼續(xù)操作怪与,如下
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(doSomething)];
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if (sel == @selector(doSomething)) {
NSLog(@"add method here");
class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:");
returnYES;
}
return [super resolveInstanceMethod:sel];
}
void dynamicMethodIMP (id self, SEL _cmd) {
NSLog(@"doSomething SEL");
}
導入了<objc/runtime.h>并且在 + (BOOL)resolveInstanceMethod:(SEL)sel 中執(zhí)行了 class_addMethod 這個方法夺刑,然后定義了一個void dynamicMethodIMP (id self, SEL _cmd)這個函數(shù),運行工程,看log
**2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] add method here**
**2015-12-24 11:45:11.934 RuntimeTest1[2284:478571] doSomething SEL**
這時候我們發(fā)現(xiàn)遍愿,程序并沒有崩潰存淫,而且還輸出了doSomething SEL
這時候就說明我們已經(jīng)通過runtime成功的向我們這個類中添加了一個方法。
關于class_addMethod這個方法的定義
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
- cls 在這個類中添加方法沼填,也就是需要添加方法的類
- name 方法名
- imp 本質(zhì)上就是一個函數(shù)指針桅咆,指向方法的實現(xiàn)
- types 定義該數(shù)返回值類型和參數(shù)類型的字符串,這里比如"v@:"坞笙,其中v就是void岩饼,帶表返回類型就是空,@代表參數(shù)薛夜,這里指的是id(self)籍茧,這里:指的是方法SEL(_cmd),比如我再定義一個函數(shù)
int newMethod (id self, SEL _cmd, NSString *str) {
return 100;
}
那么添加這個函數(shù)的方法就應該是
ass_addMethod([self class], @selector(newMethod), (IMP)newMethod, "i@:@");
4.如果在+ (BOOL)resolveInstanceMethod:(SEL)sel中沒有找到或者添加方法
那么,消息繼續(xù)往下傳遞到- (id)forwardingTargetForSelector:(SEL)aSelector
重新建個工程梯澜,然后增加一個叫SecondViewController的類寞冯,里面添加一個- (void)secondVCMethod方法,如下
在SecondViewController中
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)secondVCMethod {
NSLog(@"This is secondVC method !");
}
在ViewController中
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(secondVCMethod)];
}
運行結果,崩潰
reason: '-[ViewCon
troller secondVCMethod]: unrecognized selector sent to instance 0x7fc3a8535c10'**
5.在ViewController中實現(xiàn) forwardingTargetForSelector:(SEL)aSelector 方法后,解決崩潰
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:@selector(secondMethod)];
}
- (id)forwardingTargetForSelector:(SEL)aSelector {
//先得到第二個控制器的類
Class class = NSClassFromString(@"SecondViewController");
//創(chuàng)建新的控制器
UIViewController *VC = [class new];
//如果方法名相同,就實現(xiàn)方法
if (aSelector == NSSelectorFromString(@"secondMethod")) {
NSLog(@"secondMethod will do it");
return VC;
}
return nil;
}
+ (BOOL)resolveInstanceMethod:(SEL)sel{
return [super resolveInstanceMethod:sel];
}
運行結果
**2015-12-24 14:00:34.168 RuntimeTest2[3284:870957] secondVC do this !**
**2015-12-24 14:00:34.169 RuntimeTest2[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 !");
return vc;
}
return nil;
}
在沒有找到 - (void)secondVCMethod 這個方法的時候晚伙,消息繼續(xù)傳遞吮龄,直到 - (id)forwardingTargetForSelector:(SEL)aSelector ,然后我在里面創(chuàng)建了一個SecondViewController的對象咆疗,并且判斷如果有這個方法漓帚,就返回SecondViewController的對象。這個函數(shù)就是消息的轉(zhuǎn)發(fā)午磁,在這兒我們成功的把消息傳給了SecondViewController尝抖,然后讓它來執(zhí)行,所以就執(zhí)行了那個方法漓踢。同時,也相當于完成了一個多繼承漏隐!
可以通過message forwarding 去實現(xiàn) one-to-N的delegates
runtime的使用場景
1.字典轉(zhuǎn)模型
篇幅一:
NSDictionary *dict = @{@"name":@"itcast",@"age":@18,@"height":@1.7};
unsigned int count = 0;
Ivar *Ivars = class_copyIvarList([CZPerson class], &count);
CZPerson *person = [CZPerson new];
for (int i = 0; i < count; ++i) {
Ivar var = Ivars[i];
const char *str = ivar_getName(var);
NSMutableString *strName = [NSMutableString stringWithString:[NSString stringWithUTF8String:str]];
NSString *name = [strName substringFromIndex:1];
[person setValue:dict[name] forKey:name];
}
NSLog(@"%@ %d %f",person.name,person.age,person.height);
篇幅二: 小馬哥
* 思路:利用運行時喧半,遍歷模型中所有屬性,根據(jù)模型的屬性名青责,去字典中查找key挺据,取出對應的值,給模型的屬性賦值脖隶。
* 步驟:提供一個NSObject分類扁耐,專門字典轉(zhuǎn)模型,以后所有模型都可以通過這個分類轉(zhuǎn)产阱。
@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];
// 獲取字典數(shù)組
NSArray *dictArr = statusDict[@"statuses"];
// 自動生成模型的屬性字符串
// [NSObject resolveDict:dictArr[0][@"user"]];
_statuses = [NSMutableArray array];
// 遍歷字典數(shù)組
for (NSDictionary *dict in dictArr) {
Status *status = [Status modelWithDict:dict];
[_statuses addObject:status];
}
// 測試數(shù)據(jù)
NSLog(@"%@ %@",_statuses,[_statuses[0] user]);
}
@end
@implementation NSObject (Model)
+ (instancetype)modelWithDict:(NSDictionary *)dict
{
// 思路:遍歷模型中所有屬性-》使用運行時
// 0.創(chuàng)建對應的對象
id objc = [[self alloc] init];
// 1.利用runtime給對象中的成員屬性賦值
// class_copyIvarList:獲取類中的所有成員屬性
// Ivar:成員屬性的意思
// 第一個參數(shù):表示獲取哪個類中的成員屬性
// 第二個參數(shù):表示這個類有多少成員屬性婉称,傳入一個Int變量地址,會自動給這個變量賦值
// 返回值Ivar *:指的是一個ivar數(shù)組,會把所有成員屬性放在一個數(shù)組中王暗,通過返回的數(shù)組就能全部獲取到悔据。
/* 類似下面這種寫法
Ivar ivar;
Ivar ivar1;
Ivar ivar2;
// 定義一個ivar的數(shù)組a
Ivar a[] = {ivar,ivar1,ivar2};
// 用一個Ivar *指針指向數(shù)組第一個元素
Ivar *ivarList = a;
// 根據(jù)指針訪問數(shù)組第一個元素
ivarList[0];
*/
unsigned int count;
// 獲取類中的所有成員屬性
Ivar *ivarList = class_copyIvarList(self, &count);
for (int i = 0; i < count; i++) {
// 根據(jù)角標,從數(shù)組取出對應的成員屬性
Ivar ivar = ivarList[i];
// 獲取成員屬性名
NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 處理成員屬性名->字典中的key
// 從第一個角標開始截取
NSString *key = [name substringFromIndex:1];
// 根據(jù)成員屬性名去字典中查找對應的value
id value = dict[key];
// 二級轉(zhuǎn)換:如果字典中還有字典俗壹,也需要把對應的字典轉(zhuǎn)換成模型
// 判斷下value是否是字典
if ([value isKindOfClass:[NSDictionary class]]) {
// 字典轉(zhuǎn)模型
// 獲取模型的類對象科汗,調(diào)用modelWithDict
// 模型的類名已知,就是成員屬性的類型
// 獲取成員屬性類型
NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
// 生成的是這種@"@\"User\"" 類型 -》 @"User" 在OC字符串中 \" -> "绷雏,\是轉(zhuǎn)義的意思头滔,不占用字符
// 裁剪類型字符串
NSRange range = [type rangeOfString:@"\""];
type = [type substringFromIndex:range.location + range.length];
range = [type rangeOfString:@"\""];
// 裁剪到哪個角標,不包括當前角標
type = [type substringToIndex:range.location];
// 根據(jù)字符串類名生成類對象
Class modelClass = NSClassFromString(type);
if (modelClass) { // 有對應的模型才需要轉(zhuǎn)
// 把字典轉(zhuǎn)模型
value = [modelClass modelWithDict:value];
}
}
// 三級轉(zhuǎn)換:NSArray中也是字典涎显,把數(shù)組中的字典轉(zhuǎn)換成模型.
// 判斷值是否是數(shù)組
if ([value isKindOfClass:[NSArray class]]) {
// 判斷對應類有沒有實現(xiàn)字典數(shù)組轉(zhuǎn)模型數(shù)組的協(xié)議
if ([self respondsToSelector:@selector(arrayContainModelClass)]) {
// 轉(zhuǎn)換成id類型坤检,就能調(diào)用任何對象的方法
id idSelf = self;
// 獲取數(shù)組中字典對應的模型
NSString *type = [idSelf arrayContainModelClass][key];
// 生成模型
Class classModel = NSClassFromString(type);
NSMutableArray *arrM = [NSMutableArray array];
// 遍歷字典數(shù)組,生成模型數(shù)組
for (NSDictionary *dict in value) {
// 字典轉(zhuǎn)模型
id model = [classModel modelWithDict:dict];
[arrM addObject:model];
}
// 把模型數(shù)組賦值給value
value = arrM;
}
}
if (value) { // 有值棺禾,才需要給模型的屬性賦值
// 利用KVC給模型中的屬性賦值
[objc setValue:value forKey:key];
}
}
return objc;
}
@end
2.歸檔解檔
篇幅一:
// 歸檔
- (void)encodeWithCoder:(NSCoder *)enCoder{
// 取得所有成員變量名
NSArray *properNames = [[self class] propertyOfSelf];
for (NSString *propertyName in properNames) {
// 創(chuàng)建指向get方法
SEL getSel = NSSelectorFromString(propertyName);
// 對每一個屬性實現(xiàn)歸檔
[enCoder encodeObject:[self performSelector:getSel] forKey:propertyName];
}
}
// 解檔
- (id)initWithCoder:(NSCoder *)aDecoder{
// 取得所有成員變量名
NSArray *properNames = [[self class] propertyOfSelf];
for (NSString *propertyName in properNames) {
// 創(chuàng)建指向?qū)傩缘膕et方法
// 1.獲取屬性名的第一個字符缀蹄,變?yōu)榇髮懽帜? NSString *firstCharater = [propertyName substringToIndex:1].uppercaseString;
// 2.替換掉屬性名的第一個字符為大寫字符,并拼接出set方法的方法名
NSString *setPropertyName = [NSString stringWithFormat:@"set%@%@:",firstCharater,[propertyName substringFromIndex:1]];
SEL setSel = NSSelectorFromString(setPropertyName);
[self performSelector:setSel withObject:[aDecoder decodeObjectForKey:propertyName]];
}
return self;
}
篇幅二:
原理描述:用runtime提供的函數(shù)遍歷Model自身所有屬性膘婶,并對屬性進行encode和decode操作缺前。
核心方法:在Model的基類中重寫方法:
- (void)encodeWithCoder:(NSCoder *)aCoder {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[aCoder encodeObject:[self valueForKey:key] forKey:key];
}
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
unsigned int outCount;
Ivar * ivars = class_copyIvarList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}
3.runtime交換方法
* 開發(fā)使用場景:系統(tǒng)自帶的方法功能不夠,給系統(tǒng)自帶的方法擴展一些功能悬襟,并且保持原有的功能衅码。
* 方式一:繼承系統(tǒng)的類,重寫方法.
* 方式二:使用runtime,交換方法.
@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的實現(xiàn)割捅,就能調(diào)用imageWithName奶躯,間接調(diào)用imageWithName的實現(xiàn)。
UIImage *image = [UIImage imageNamed:@"123"];
}
@end
@implementation UIImage (Image)
// 加載分類到內(nèi)存的時候調(diào)用
+ (void)load
{
// 交換方法
// 獲取imageWithName方法地址
Method imageWithName = class_getClassMethod(self, @selector(imageWithName:));
// 獲取imageWithName方法地址
Method imageName = class_getClassMethod(self, @selector(imageNamed:));
// 交換方法地址亿驾,相當于交換實現(xiàn)方式
method_exchangeImplementations(imageWithName, imageName);
}
// 不能在分類中重寫系統(tǒng)方法imageNamed嘹黔,因為會把系統(tǒng)的功能給覆蓋掉,而且分類中不能調(diào)用super.
// 既能加載圖片又能打印
+ (instancetype)imageWithName:(NSString *)name
{
// 這里調(diào)用imageWithName莫瞬,相當于調(diào)用imageName
UIImage *image = [self imageWithName:name];
if (image == nil) {
NSLog(@"加載空的圖片");
}
return image;
}
@end
4.動態(tài)添加方法 (可以用于 “代理”)
* 開發(fā)使用場景:如果一個類方法非常多儡蔓,加載類到內(nèi)存的時候也比較耗費資源,需要給每個方法生成映射表疼邀,可以使用動態(tài)給某個類喂江,添加方法解決。
* 經(jīng)典面試題:有沒有使用performSelector旁振,其實主要想問你有沒有動態(tài)添加過方法获询。
* 簡單使用
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *p = [[Person alloc] init];
// 默認person涨岁,沒有實現(xiàn)eat方法,可以通過performSelector調(diào)用筐付,但是會報錯卵惦。
// 動態(tài)添加方法就不會報錯
[p performSelector:@selector(eat)];
}
@end
@implementation Person
// void(*)()
// 默認方法都有兩個隱式參數(shù),
void eat(id self,SEL sel)
{
NSLog(@"%@ %@",self,NSStringFromSelector(sel));
}
// 當一個對象調(diào)用未實現(xiàn)的方法瓦戚,會調(diào)用這個方法處理,并且會把對應的方法列表傳過來.
// 剛好可以用來判斷沮尿,未實現(xiàn)的方法是不是我們想要動態(tài)添加的方法
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == @selector(eat)) {
// 動態(tài)添加eat方法
// 第一個參數(shù):給哪個類添加方法
// 第二個參數(shù):添加方法的方法編號
// 第三個參數(shù):添加方法的函數(shù)實現(xiàn)(函數(shù)地址)
// 第四個參數(shù):函數(shù)的類型,(返回值+參數(shù)類型) v:void @:對象->self :表示SEL->_cmd
class_addMethod(self, @selector(eat), eat, "v@:");
}
return [super resolveInstanceMethod:sel];
}
@end
5.動態(tài)添加屬性
* 原理:給一個類聲明屬性较解,其實本質(zhì)就是給這個類添加關聯(lián)畜疾,并不是直接把這個值的內(nèi)存空間添加到類存空間。
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 給系統(tǒng)NSObject類動態(tài)添加屬性name
NSObject *objc = [[NSObject alloc] init];
objc.name = @"小碼哥";
NSLog(@"%@",objc.name);
}
@end
// 定義關聯(lián)的key
static const char *key = "name";
@implementation NSObject (Property)
- (NSString *)name
{
// 根據(jù)關聯(lián)的key印衔,獲取關聯(lián)的值啡捶。
return objc_getAssociatedObject(self, key);
}
- (void)setName:(NSString *)name
{
// 第一個參數(shù):給哪個對象添加關聯(lián)
// 第二個參數(shù):關聯(lián)的key铭腕,通過這個key獲取
// 第三個參數(shù):關聯(lián)的value
// 第四個參數(shù):關聯(lián)的策略
objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
6.Json到Model的轉(zhuǎn)化
原理描述:用runtime提供的函數(shù)遍歷Model自身所有屬性致份,如果屬性在json中有對應的值,則將其賦值滓窍。
核心方法:在NSObject的分類中添加方法:
- (instancetype)initWithDict:(NSDictionary *)dict {
if (self = [self init]) {
//(1)獲取類的屬性及屬性對應的類型
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * attributes = [NSMutableArray array];
/*
* 例子
* name = value3 attribute = T@"NSString",C,N,V_value3
* name = value4 attribute = T^i,N,V_value4
*/
unsigned int outCount;
objc_property_t * properties = class_copyPropertyList([self class], &outCount);
for (int i = 0; i < outCount; i ++) {
objc_property_t property = properties[i];
//通過property_getName函數(shù)獲得屬性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通過property_getAttributes函數(shù)可以獲得屬性的名字和@encode編碼
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即釋放properties指向的內(nèi)存
free(properties);
//(2)根據(jù)類型給屬性賦值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}