给Model优化赋值(Runtime运行状态)

2017-08-21  本文已影响0人  子小每文

1:首先建一个继承NSObject类

- (id)initWithDic:(NSDictionary*)dict{

self = [super init];

if (self) {

[self setAttributesDictionary:dict];  //

}

return self;

}

//下面这个方法需要在子类里面重写次方法(想写就写,不写也行,自己调试)

- (NSDictionary *)attributeMapDictionary{

//子类需要重写的方法

//下面这个方法验证类,返回字典 可以写.也可以不写

#define SHOULDOVERRIDE(basename, subclassname){ NSAssert([basename isEqualToString:subclassname], @"subclass should override the method!");}

//NSAssert(NO, "You should override this method in Your Custom Class");

return nil;

}

//最关键的就是下面这个方法了   如果子类不重写上面那个方法,对dict进行判断

//return nil  不写SHOULDOVERRIDE(basename, subclass name)一直返回nil

- (void)setAttributesDictionary:(NSDictionary *)aDict{

NSDictionary *mapDictionary = [self attributeMapDictionary];

if (mapDictionary == nil) {

NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithCapacity:aDict.count];

for (NSString *key in aDict) {

[tempDict setObject:key forKey:key];

}

mapDictionary = tempDict;

}

NSEnumerator *mEnumerator = [mapDictionary keyEnumerator];

id attributeName = nil;

while ((attributeName = [mEnumerator nextObject])) {

SEL setter = [self _getSetterWithAttributeName:attributeName];

if ([self respondsToSelector:setter]) {

NSString *Key = [mapDictionary objectForKey:attributeName];

id AllValue = [aDict objectForKey:Key];

//这个会创建一个新的线程实行函数,并传入参数AllValue,并且会等待函数退出后再继续执行。 runtime状态

[self performSelectorOnMainThread:setter withObject:AllValue waitUntilDone:[NSThread isMainThread]];

}

}

}

- (SEL)_getSetterWithAttributeName:(NSString *)attributeName

{

NSString *firstAlpha = [[attributeName substringToIndex:1] uppercaseString];

NSString *otherAlpha = [attributeName substringFromIndex:1];

NSString *setterMethodName = [NSString stringWithFormat:@"set%@%@:", firstAlpha, otherAlpha];

return NSSelectorFromString(setterMethodName);

}

上一篇 下一篇

猜你喜欢

热点阅读