利用runtime解析model
by 伍雪颖
+ (instancetype)modelWithDictionary:
(NSDictionary
*) data{
return [[self
alloc]
initWithDictionary:data];
}
- (instancetype)initWithDictionary: (NSDictionary
*) data{
{
self = [super
init];
if (self) {
[self
assginToPropertyWithDictionary:data];
}
return
self;
}
}
-(void) assginToPropertyWithDictionary: (NSDictionary
*) data{
if (data ==
nil) {
return;
}
NSArray *dicKey = [data
allKeys];
for (int
i =
0; i < dicKey.count; i ++) {
SEL setSel = [self
creatSetterWithPropertyName:dicKey[i]];
if ([self
respondsToSelector:setSel]) {
NSString *value = [NSString
stringWithFormat:@"%@",
data[dicKey[i]]];
[self
performSelectorOnMainThread:setSel
withObject:value
waitUntilDone:[NSThread
isMainThread]];
}
}
}
- (SEL) creatSetterWithPropertyName: (NSString
*) propertyName{
propertyName = propertyName.capitalizedString;
propertyName = [NSString
stringWithFormat:@"set%@:",
propertyName];
return
NSSelectorFromString(propertyName);
}
版权声明:本文为博主原创文章,未经博主允许不得转载。