iOS runtime實戰應用:Method Swizzling
以下屬於我的摘着和學習
iOS內功篇:runtime
runtime是一個c和彙編寫的動態庫,它就像一個小小的系統,將OC和C緊密關聯;這個系統主要做兩件事
- 封裝C語言的結構體和函數,讓開發者在運行時創建、檢查或修改類,對象和方法等等。
- 傳遞消息,找出方法的最終執行代碼。
栗子:
[student walkTheDog];
那麼runtime會將它轉化成C語言的代碼
objc_msgSend(student, @selector(walkTheDod));
這個方法就是發送消息的方法,類似這樣的方法runtime提供了很多,比如:
// 獲取屬性列表
objc_property_t * class_copyPropertyList ( Class cls, unsigned int *outCount );
// 獲取所有方法的數組
Method * class_copyMethodList ( Class cls, unsigned int *outCount );
// 添加方法
BOOL class_addMethod ( Class cls, SEL name, IMP imp, const char *types );
那麼我們可以利用這些方法乾點什麼?
方法調用流程
1> 遍歷對象的屬性
比如;看看student的有哪些屬性(性別,生日)
2> 動態添加/修改屬性,動態添加/修改/替換方法
比如: 修改student的性別,生日日期,walkTheDog(變成study)
3> 動態創建Class/Object/Protocol等等...
4> 方法攔截調用(修改實現/添加實現)
比如:Student1發送一個walkTheDog消息, 而walkTheDog方法沒有實現,我們可以通過runtime攔截,給方法動態添加一個實現,甚至可以讓其他對象Student2來walkTheDog;
下面以實例對象調用 student walkTheDog
爲栗子描述方法調用流程:
1> 編譯器會把`student walkTheDog` 轉化爲objc_msgSend(student,@seletor(walkTheDog))
2> `runtime` 會在student實例對象所對應的Student類的方法緩存列表裏查找方法SEL
3> 如果沒有找到,則在Student類的方法分發表查找方法的SEL。(類由對象isa指針指向,方法分發表即methodList)
4> 如果沒有找到,則在其父類的方法分發表裏查找方法的SEL(父類由類的superClass指向 [self和super區別](http://blog.csdn.net/li15809284891/article/details/54836905)),如果一直沒找到,會到達NSObject基類,最終沒有改方法則編譯器報錯。
5> 如果使用`student preformSelector:@selector:(walkTheDog)`的方式調用方法,需要到運行時才能確定對象能否接收指定的消息,這個時候會進入消息轉發流程
消息轉發流程
1> 動態方法解析
接收到位置消息時(假設student的walkTheDog方法尚未實現), runtime 會調用 +resolveInstanceMethod:
(實例方法)或者+resolveClassMethod:
(類方法),在該方法中,我們可以給未知消息新增一個已經實現的方法。
void study(id self, SEL _cmd) {
//let the student study
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
NSString *selString = NSStingFormSelector(sel);
if ([selString isEqualToString:@"walkTheDog"]){
class_addMethod(self.class, @selector(walkTheDog), (IMP)study, "@:");
}
return [super resolveInstanceMethod:sel];
}
2> 備用接收者
如果以上方法都沒有做處理, runtime會調用 - (id)forwardingTargetForSelector:(SEL)aSelector
方法。
如果該方法返回了一個非nil (也不是self)的對象,而且該對象實現了這個方法,那麼這個對象就成了消息的接收者,消息就被分發到該對象。
適用情況: 通常在對象內部使用,讓內部的另一個對象處理消息,在外面看起來就像是對象處理了消息。
-(id)forwardTargetForSelector:(SEL)aSelector {
NSString *selString = NSStringFromSelector(aSelector);
if ([selString isEquaToString:@"walkTheDog"])
return self.student2;
}
return [super forwardingTargetSelector:aSelector];
}
3> 完整消息轉發
在- (void)forwardInvocation:(NSInvocation *)anInvocation
方法中選擇轉發消息的對象,其中anInvocation對象封裝了未知消息的所有細節,並保留調用結果發送到原始調用者。
比如:student將消息完整轉發brother來處理
- (void)forwardInvocation:(NSInvocation *)anInvocation {
if ([Person instancesRespondToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:self.person];
}
}
4> 如果在以上三個方法都沒有處理未知消息,則會引發異常。
iOS runtime實戰應用:成員變量和屬性
成員變量
1、定義:
Ivar: 實例變量類型,是一個指向objc_ivar結構體的指針
typedef struct objc_ivar *Ivar;
2、操作函數:
// 獲取所有成員變量
class_copyIvarList
// 獲取成員變量名
ivar_getName
// 獲取成員變量類型編碼
ivar_getTypeEncoding
// 獲取指定名稱的成員變量
class_getInstanceVariable
// 獲取某個對象成員變量的值
object_getIvar
// 設置某個對象成員變量的值
object_setIvar
3、使用實例:
Model的頭文件聲明如下:
@interface Model : NSObject {
NSString * _str1;
}
@property NSString * str2;
@property (nonatomic, copy) NSDictionary * dict1;
@end
獲取其成員變量:
unsigned int outCount = 0;
// 獲取所有成員變量
Ivar * ivars = class_copyIvarList([Model class], &outCount);
for (unsigned int i = 0; i < outCount; i ++) {
Ivar ivar = ivars[i];
const char * name = ivar_getName(ivar);
const char * type = ivar_getTypeEncoding(ivar);
NSLog(@"類型爲 %s 的 %s ",type, name);
}
free(ivars);
打印結果:
[897:26127] 類型爲 @"NSString" 的 _str1
[897:26127] 類型爲 @"NSString" 的 _str2
[897:26127] 類型爲 @"NSDictionary" 的 _dict1
屬性
1、定義:
objc_property_t:聲明的屬性的類型,是一個指向objc_property結構體的指針
typedef struct objc_property *objc_property_t;
2、操作函數:
// 獲取所有屬性
class_copyPropertyList
說明:使用class_copyPropertyList並不會獲取無@property聲明的成員變量
// 獲取屬性名
property_getName
// 獲取屬性特性描述字符串
property_getAttributes
// 獲取所有屬性特性
property_copyAttributeList
說明:
property_getAttributes函數返回objc_property_attribute_t結構體列表,objc_property_attribute_t結構體包含name和value,常用的屬性如下:
屬性類型 name值:T value:變化
編碼類型 name值:C(copy) &(strong) W(weak) 空(assign) 等 value:無
非/原子性 name值:空(atomic) N(Nonatomic) value:無
變量名稱 name值:V value:變化
使用property_getAttributes獲得的描述是property_copyAttributeList能獲取到的所有的name和value的總體描述,如 T@"NSDictionary",C,N,V_dict1
3、使用實例:
unsigned int outCount = 0;
objc_property_t *porperties = class_copyProperList([Model class], &outCount):
for (unsigned int i = 0, i<outCount; i++) {
objc_property_t property = properties[i];
//屬性名
const char *name = property_getName(property);
//屬性描述
const char *propertyAttr = proper_getAttributes(property);
NSLog(@"屬性描述爲 %s 的 %s", propertyAttr, name);
//屬性的特性
unsigned int attrCount = 0;
objc_property_attribute_t * attrs = property_copyAttributeList(property, &attrCount);
for (unsigned int j = 0; j < attrCount; j ++) {
objc_property_attribute_t attr = attrs[j];
const char * name = attr.name;
const char * value = attr.value;
NSLog(@"屬性的描述:%s 值:%s", name, value);
}
free(attrs);
NSLog(@"\n");
}
free(properties);
}
打印結果:
text[1202:55532] 屬性名: str2 屬性描述: T@"NSString",&,V_str2
text[1202:55532] 屬性名: T 值:@"NSString"
text[1202:55532] 屬性名: & 值:
text[1202:55532] 屬性名: V 值:_str2
text[1202:55532]
text[1202:55532] 屬性名: dict1 屬性描述: T@"NSDictionary",C,N,V_dict1
text[1202:55532] 屬性名: T 值:@"NSDictionary"
text[1202:55532] 屬性名: C 值:
text[1202:55532] 屬性名: N 值:
text[1202:55532] 屬性名: V 值:_dict1
text[1202:55532]
應用實例
1、簡單的JSON轉模型
- (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函數獲得屬性的名字
NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
[keys addObject:propertyName];
//通過property_getAttributes函數可以獲得屬性的名字和@encode編碼
NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
[attributes addObject:propertyAttribute];
}
//立即釋放properties指向的內存
free(properties);
//(2)根據類型給屬性賦值
for (NSString * key in keys) {
if ([dict valueForKey:key] == nil) continue;
[self setValue:[dict valueForKey:key] forKey:key];
}
}
return self;
}
2、快速歸檔
- (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;
}
- (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];
}
}
3、訪問私有變量
Ivar ivar = class_getInstanceVariable([Model class], "_str1");
NSString * str1 = object_getIvar(model, ivar);