#ifndef define_h
#define define_h
#import <objc/runtime.h>
#define DECLEAR_NSCodingMethods() \
\
- (id)initWithCoder:(NSCoder *)coder\
{\
Class cls = [self class];\
while (cls != [NSObject class]) {\
/*判斷是自身類還是父類*/\
BOOL bIsSelfClass = (cls == [self class]);\
unsigned int iVarCount = 0;\
unsigned int propVarCount = 0;\
unsigned int sharedVarCount = 0;\
Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*變量列表,含屬性以及私有變量*/\
objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*屬性列表*/\
sharedVarCount = bIsSelfClass ? iVarCount : propVarCount;\
\
for (int i = 0; i < sharedVarCount; i++) {\
const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i));\
NSString *key = [NSString stringWithUTF8String:varName];\
id varValue = [coder decodeObjectForKey:key];\
NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"];\
if (varValue && [filters containsObject:key] == NO) {\
[self setValue:varValue forKey:key];\
}\
}\
free(ivarList);\
free(propList);\
cls = class_getSuperclass(cls);\
}\
return self;\
}\
\
- (void)encodeWithCoder:(NSCoder *)coder\
{\
Class cls = [self class];\
while (cls != [NSObject class]) {\
/*判斷是自身類還是父類*/\
BOOL bIsSelfClass = (cls == [self class]);\
unsigned int iVarCount = 0;\
unsigned int propVarCount = 0;\
unsigned int sharedVarCount = 0;\
Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*變量列表,含屬性以及私有變量*/\
objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*屬性列表*/\
sharedVarCount = bIsSelfClass ? iVarCount : propVarCount;\
\
for (int i = 0; i < sharedVarCount; i++) {\
const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i));\
NSString *key = [NSString stringWithUTF8String:varName];\
/*valueForKey只能獲取本類所有變量以及所有層級父類的屬性,不包含任何父類的私有變量(會崩潰)*/\
id varValue = [self valueForKey:key];\
NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"];\
if (varValue && [filters containsObject:key] == NO) {\
[coder encodeObject:varValue forKey:key];\
}\
}\
free(ivarList);\
free(propList);\
cls = class_getSuperclass(cls);\
}\
}
#endif /* define_h */
利用運行時 進行模型的歸解檔
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 利用運行時,歸檔解歸檔實現用戶信息存儲,無需對用戶模型的每個屬性單獨歸檔與解歸檔:1、使用方法:保存:UserMo...
- 用運行時,以后這兩個方法可以到處拷貝,不需要添加N行的重復代碼,也不用擔心屬性變化后這里忘記修改。 class_c...