使用runtime json轉model

自己最近在學習runtime,希望在學習過程中做些記錄,方便自己后來溫習查閱。也希望能幫助到別的同學。

在你的model中直接使用以下方法

好了,直接上代碼

-(instancetype)initWithDictionary:(NSDictionary *)dic

{

? ? if (self = [super init])

? ? {

? ? ? ? NSMutableArray *keys = [NSMutableArray array];

? ? ? ? unsigned int property_count;

? ? ? ? // 獲取屬性列表,注意入參

? ? ? ? objc_property_t *properties = class_copyPropertyList([self class], &property_count);

? ? ? ? for (int i = 0; i< property_count; i++)

? ? ? ? {

? ? ? ? ? ? objc_property_t property = properties[i];

? ? ? ? ? ? //通過property_getName 函數獲取屬性名字

? ? ? ? ? ? NSString *peopertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];

? ? ? ? ? ? [keys addObject:peopertyName];

? ? ? ? }

? ? ? ? //釋放properties指向的內存

? ? ? ? free(properties);

? ? ? ? for (NSString *key in keys)

? ? ? ? {

? ? ? ? ? ? if ([dic valueForKey:key] == nil)

? ? ? ? ? ? ? ? continue;

? ? ? ? ? ? [self setValue:[dic valueForKey:key] forKey:key];

? ? ? ? }

? ? }

? ? return self;

}

代碼很簡單。

使用class_copyPropertyList()函數獲取屬性列表,入參為class和一個int數據的地址。代用該函數會修改這個int參數。可以通過property_getName 函數獲取屬性名字,通過property_getAttribute 函數獲取屬性。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。