自己最近在學習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 函數獲取屬性。