標籤:
第一次看到runtime時,覺得太高大上,動態擷取方法、屬性等簡直厲害的不要不要的。在經過尋找資料+實踐後,發現runtime並沒有想象中那麼複雜,接下來對runtime進行基本的介紹。
要使用運行時方法需要引入runtime.h檔案
一、基礎知識
Method :成員方法
Ivar : 成員變數
二、常用方法
class_copyPropertyList : 擷取屬性列表
class_copyMethodList : 擷取成員方法列表
class_copyIvarList:擷取成員變數列表
ivar_getName:擷取變數名
property_getName:擷取屬性名稱
使用樣本:
1.擷取成員變數列表
//1.擷取變數list unsigned int ivarCount = 0; //成員變數數 Ivar *ivarList = class_copyIvarList([self class], &ivarCount);//ivar數組 for (int i = 0; i < ivarCount; i++) {//遍曆 Ivar ivar = ivarList[i]; //擷取ivar const char *name = ivar_getName(ivar);//擷取變數名 NSString *key = [NSString stringWithUTF8String:name]; NSLog(@"%@", key); }
free(ivarList);
2.擷取屬性列表
unsigned int count = 0; objc_property_t *propertList = class_copyPropertyList([self class], &count); for (int i = 0; i < count; i++) { objc_property_t property = propertList[i]; const char *name = property_getName(property); const char *attrs = property_getAttributes(property);// property_copyAttributeValue(,) 第一個參數為objc_property_t,第二個參數"V"擷取變數名,"T"擷取類型 const char *value = property_copyAttributeValue(property, "V"); NSLog(@"name = %s, attrs = %s, value = %s", name, attrs, value); }
free(propertList);
3.擷取方法列表
unsigned int count = 0; Method *methodList = class_copyMethodList([self class], &count); for (int i = 0 ; i < count; i++) { Method method = methodList[i]; SEL selector = method_getName(method);//方法入口 const char *sel_name = sel_getName(selector); NSLog(@"方法名 %s", sel_name); } free(methodList);
三、使用方向:歸檔、字典<---->模型、架構封裝等
實現歸檔
#define WKCodingImplementing - (void)encodeWithCoder:(NSCoder *)aCoder { unsigned int ivarCount = 0; Ivar *ivarList = class_copyIvarList([self class], &ivarCount); for (int i = 0; i < ivarCount; i++) { Ivar ivar = ivarList[i]; const char *name = ivar_getName(ivar); const char *type = ivar_getTypeEncoding(ivar); NSLog(@"%s-----%s", name, type); NSString *key = [NSString stringWithUTF8String:name]; id value = [self valueForKey:key]; [aCoder encodeObject:value forKey:key]; } free(ivarList); } - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { unsigned int ivarCount = 0; Ivar *ivarList = class_copyIvarList([self class], &ivarCount); for (int i = 0; i < ivarCount; i++) { Ivar ivar = ivarList[i]; const char *name = ivar_getName(ivar); NSString *key = [NSString stringWithUTF8String:name]; NSLog(@"%@ %@", key, value); id value = [aDecoder decodeObjectForKey:key]; [self setValue:value forKey:key]; } } return self; }
iOS進階:Objective-C runtime(一)