前言:
我們知道Objective-C調用方法是一種發消息的機制,編譯器會把 [target doMethodWith:var1];轉換為
objc_msgSend(target,@selector(doMethodWith:),var1)。本文簡單介紹一下Runtime概念,并著重總結一下Runtime的實用技能。
一、Runtime基本概念
- RunTime簡稱運行時,就是系統在運行的時候的一些機制,其中最主要的是消息機制。
- 對于C語言,函數的調用在編譯的時候會決定調用哪個函數,編譯完成之后直接順序執行,無任何二義性。
- OC的函數調用成為消息發送。屬于動態調用過程。在編譯的時候并不能決定真正調用哪個函數(事實證明,在編 譯階段,OC可以調用任何函數,即使這個函數并未實現,只要申明過就不會報錯。而C語言在編譯階段就會報錯)。
- 只有在真正運行的時候才會根據函數的名稱找 到對應的函數來調用。
1、什么是runtime?
runtime是一套底層的C語言API,包含很多強大實用的C語言數據類型和C語言函數,平時我們編寫的OC代碼,底層都是基于runtime實現的。
runtime 是開源的,任何時候你都能從 http://opensource.apple.com. 獲取。事實上查看 Objective-C 源碼是理解它是如何工作的第一種方式,在這個問題上要比讀蘋果的文檔要好。你可以下載適合 Mac OS X 10.6.2 的 objc4-437.1.tar.gz。(譯注:最新objc4-551.1.tar.gz)
2、常用頭文件
#import <objc/runtime.h> 包含對類、成員變量、屬性、方法的操作
#import <objc/message.h> 包含消息機制
3、常用方法
class_copyIvarList()返回一個指向類的成員變量數組的指針
class_copyPropertyList()返回一個指向類的屬性數組的指針
二、實用技能
看到上面的截圖可知Runtime的強大,方法組合幾乎無所不能,拋磚引玉,結合相關資料和經驗總結runtime比較常用的幾個技能:
1. 獲取類的全部成員變量
2. 獲取類的全部屬性名
3. 獲取類的全部方法
4. 獲取類遵循的全部協議
5. 動態改變成員變量
6. 動態交換類的方法
7. 動態添加新方法
8. 讓category能夠添加屬性
9.更便捷的歸檔/解檔
三、具體代碼實現
我們新建一個Person類。Person.h:
#import <Foundation/Foundation.h>
@protocol personDelegate <NSObject>
- (void)personPayForFun:(NSInteger)money;
@end
@interface Person : NSObject
#pragma mark -屬性
@property (nonatomic,assign) id<personDelegate> delegate;
@property (nonatomic,copy) NSString *name;//姓名
@property (nonatomic,copy) NSString *sex;//性別
@property (nonatomic,assign) NSInteger age;//年齡
@property (nonatomic,assign) float height;//身高
@property (nonatomic,copy) NSString *job;//工作
@property (nonatomic,copy) NSString *native;//籍貫
#pragma mark -方法
- (void)eat;
- (void)sleep;
- (NSString *)doSomeThing;
- (NSString *)doSomeOtherThing;
@end
person.m
#import "Person.h"
#import <objc/runtime.h>
@interface Person ()<NSCoding>
@property (nonatomic,copy) NSString *education;//學歷 私有變量
@end
@implementation Person
- (void)eat{
}
- (void)sleep{
NSLog(@"抓緊睡覺");
}
-(NSString *)doSomeThing{
return @"我要去爬山";
}
- (NSString *)doSomeOtherThing{
return @"我要去唱歌";
}
@end
1. 獲取類的全部成員變量
runtime 可以獲取一個類的所有成員變量名,包括私有的成員變量。
// 獲取類的全部成員變量
- (IBAction)function1:(id)sender {
unsigned int count;
//獲取成員變量的數組的指針
Ivar *ivars = class_copyIvarList([Person class], &count);
for (int i=0 ; i<count; i++) {
Ivar ivar = ivars[i];
//根據ivar獲得其成員變量的名稱
const char *name = ivar_getName(ivar);
//C的字符串轉OC的字符串
NSString *key = [NSString stringWithUTF8String:name];
NSLog(@"%d == %@",i,key);
}
// 記得釋放
free(ivars);
//如果你的成員私有,也可以獲取到 比如_education
}
結果:
2. 獲取類的全部屬性名
同理,我們可以獲取到一個類的全部屬性名
//獲取類的全部屬性名
- (IBAction)function2:(id)sender {
unsigned int count;
//獲得指向該類所有屬性的指針
objc_property_t *properties = class_copyPropertyList([Person class], &count);
for (int i=0 ; i<count; i++) {
//獲得該類的一個屬性的指針
objc_property_t property = properties[i];
//獲取屬性的名稱
const char *name = property_getName(property);
//將C的字符串轉為OC字符串
NSString *key = [NSString stringWithUTF8String:name];
NSLog(@"%d == %@",i,key);
}
// 記得釋放
free(properties);
}
打印結果:
3. 獲取類的全部方法
//獲取類的全部方法
- (IBAction)function3:(id)sender {
unsigned int count;
//獲取指向該類的所有方法的數組指針
Method *methods = class_copyMethodList([Person class], &count);
for (int i = 0; i < count; i++) {
//獲取該類的一個方法的指針
Method method = methods[i];
//獲取方法
SEL methodSEL = method_getName(method);
//將方法轉換為C字符串
const char *name = sel_getName(methodSEL);
//將C字符串轉為OC字符串
NSString *methodName = [NSString stringWithUTF8String:name];
//獲取方法參數個數
int arguments = method_getNumberOfArguments(method);
NSLog(@"%d == %@ %d",i,methodName,arguments);
}
//記得釋放
free(methods);
}
打印結果:
runtime中一個方法最少有兩個參數分別是 id self,SEL _cmd。
4. 獲取類遵循的全部協議
//獲取類遵循的全部協議
- (IBAction)function4:(id)sender {
unsigned int count;
//獲取指向該類遵循的所有協議的數組指針
__unsafe_unretained Protocol **protocols = class_copyProtocolList([self class], &count);
for (int i = 0; i < count; i++) {
//獲取該類遵循的一個協議指針
Protocol *protocol = protocols[i];
//獲取C字符串協議名
const char *name = protocol_getName(protocol);
//C字符串轉OC字符串
NSString *protocolName = [NSString stringWithUTF8String:name];
NSLog(@"%d == %@",i,protocolName);
}
//記得釋放
free(protocols);
}
5. 動態改變成員變量
可以修改成員變量的值,比如講person的名字從張三 改成李四。
//動態改變成員變量
- (IBAction)function5:(id)sender {
self.student.name = @"張三";
unsigned int count = 0;
Ivar *ivar = class_copyIvarList([self.student class], &count);
for (int i = 0; i<count; i++) {
Ivar var = ivar[i];
const char *varName = ivar_getName(var);
NSString *name = [NSString stringWithUTF8String:varName];
if ([name isEqualToString:@"_name"]) {
object_setIvar(self.student, var, @"李四");
break;
}
}
free(ivar);
// 結果變成了 李四
NSLog(@"student name %@",self.student.name);
}
結果:
2016-04-13 16:14:20.520 RunTimeDEMO[54516:3676553] student name 李四
6. 動態交換類的方法
可以直接修改自定義類或者系統類的方法。
//動態交換類兩個方法
- (IBAction)function6:(id)sender {
Method m1 = class_getInstanceMethod([Person class], @selector(doSomeThing));
Method m2 = class_getInstanceMethod([Person class], @selector(doSomeOtherThing));
method_exchangeImplementations(m1, m2);
// 發現兩個方交換了
NSLog(@"student do something:%@",[self.student doSomeThing]);
NSLog(@"student do doSomeOtherThing:%@",[self.student doSomeOtherThing]);
// 運行時修改的是類,不是單一對象 一次修改 在下次編譯前一直有效。
Person *student2 = [Person new];
NSLog(@"student do something:%@",[student2 doSomeThing]);
NSLog(@"student do doSomeOtherThing:%@",[student2 doSomeOtherThing]);
// 也可以在類目中添加自己方法去替換 類 或者系統類的方法
[self.student sleep];
}
結果:
2016-04-13 16:17:50.841 RunTimeDEMO[54516:3676553] student do something:我要去唱歌
2016-04-13 16:17:50.841 RunTimeDEMO[54516:3676553] student do doSomeOtherThing:我要去爬山
2016-04-13 16:17:50.841 RunTimeDEMO[54516:3676553] student do something:我要去唱歌
2016-04-13 16:17:50.841 RunTimeDEMO[54516:3676553] student do doSomeOtherThing:我要去爬山
2016-04-13 16:17:50.842 RunTimeDEMO[54516:3676553] 睡個屁起來high
1、交換自己類中的兩個方法:
在person中原來的方法是
-(NSString *)doSomeThing{
return @"我要去爬山";
}
- (NSString *)doSomeOtherThing{
return @"我要去唱歌";
}
- (void)sleep{
NSLog(@"抓緊睡覺");
}
查看上面的結果發現 doSomeThing和doSomeOtherThing交換了。
2、類目中添加自己方法去替換 類 或者系統類的方法
sleep方法變成了 起來high。是因為我在person的category Person+addProperty.m中替換了sleep方法:
// 該方法在類或分類在第一次加載內存的時候自動調用
+ (void)load
{
Method orginalMethod = class_getInstanceMethod([Person class], @selector(sleep));
Method newMethod = class_getInstanceMethod([Person class], @selector(noSleep));
method_exchangeImplementations(orginalMethod, newMethod);
}
- (void)noSleep{
NSLog(@"睡個屁起來high");
}
7. 動態添加新方法
我們給person添加一個fromCity: 的方法:
//動態添加方法
- (IBAction)function7:(id)sender {
class_addMethod([self.student class], @selector(fromCity:), (IMP)fromCityAnswer, "v@:@");
if ([self.student respondsToSelector:@selector(fromCity:)]) {
//Method method = class_getInstanceMethod([self.xiaoMing class], @selector(guess));
[self.student performSelector:@selector(fromCity:) withObject:@"廣州"];
} else{
NSLog(@"無法告訴你我從哪兒來");
}
}
void fromCityAnswer(id self,SEL _cmd,NSString *str){
NSLog(@"我來自:%@",str);
}
這里參數地方說明一下:
(IMP) fromCityAnswer 意思是fromCityAnswer的地址指針;
"v@:" 意思是,v代表無返回值void,如果是i則代表int;@代表 id sel; : 代表 SEL _cmd;
“v@:@” 意思是,一個參數的沒有返回值。
控制臺結果:
2016-04-13 16:27:59.401 RunTimeDEMO[54516:3676553] 我來自:廣州
8. 讓category能夠添加屬性
通過runtime 可以讓category添加屬性。是不是很棒的技能。
1、創建一個person的 category。
Person+addProperty.h
#import "Person.h"
@interface Person (addProperty)
// 英文名
@property (nonatomic, copy) NSString *englishName;
@end
2、Person+addProperty.m 中動態添加屬性和實現方法
#import "Person+addProperty.h"
#import <objc/runtime.h>
@implementation Person (addProperty)
char eName;
- (void)setEnglishName:(NSString *)englishName
{
objc_setAssociatedObject(self, &eName, englishName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)englishName
{
return objc_getAssociatedObject(self, &eName);
}
3、使用english屬性 而原來person 是沒有EnglishName這個屬性的。
self.student.englishName = @"xiaoMu Wang";
NSLog(@"Student English name is %@",self.student.englishName);
9.更便捷的歸檔/解檔
歸檔是存取數據的常用方法 參考:iOS歸檔
但是對于自定義對象的話在遵循NSCoding 協議,重寫兩個方法時候比較麻煩。
runtime有更好的方法解決這個問題,并且實現字典模型的自動轉換。
在person.m中實現下面兩個方法:
//注意:歸檔解檔需要遵守<NSCoding>協議,實現以下兩個方法
- (void)encodeWithCoder:(NSCoder *)encoder{
//歸檔存儲自定義對象
unsigned int count = 0;
//獲得指向該類所有屬性的指針
objc_property_t *properties = class_copyPropertyList([Person class], &count);
for (int i =0; i < count; i ++) {
//獲得
objc_property_t property = properties[i];
//根據objc_property_t獲得其屬性的名稱--->C語言的字符串
const char *name = property_getName(property);
NSString *key = [NSString stringWithUTF8String:name];
// 編碼每個屬性,利用kVC取出每個屬性對應的數值
[encoder encodeObject:[self valueForKeyPath:key] forKey:key];
}
}
- (instancetype)initWithCoder:(NSCoder *)decoder{
//歸檔存儲自定義對象
unsigned int count = 0;
//獲得指向該類所有屬性的指針
objc_property_t *properties = class_copyPropertyList([Person class], &count);
for (int i =0; i < count; i ++) {
objc_property_t property = properties[i];
//根據objc_property_t獲得其屬性的名稱--->C語言的字符串
const char *name = property_getName(property);
NSString *key = [NSString stringWithUTF8String:name];
//解碼每個屬性,利用kVC取出每個屬性對應的數值
[self setValue:[decoder decodeObjectForKey:key] forKeyPath:key];
}
return self;
}
代碼調用:
//更便捷的歸檔/解檔
- (IBAction)function9:(id)sender {
Person *person = [[Person alloc] init];
person.name = @"小木—boy";
person.sex = @"男";
person.age = 25;
person.height = 180;
person.job = @"iOS工程師";
person.native = @"北京";
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [NSString stringWithFormat:@"%@/archive",docPath];
[NSKeyedArchiver archiveRootObject:person toFile:path];
Person *unarchiverPerson = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"unarchiverPerson == %@ %@",path,unarchiverPerson);
}
控制臺結果:
讀完本文,相信你已經對runtime有了個比較簡單的認識。demo稍后更新。
源碼地址:
** * https://github.com/yinwentao/RunTimeDEMO.git * **