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

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);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,838评论 0 9
  • 本文结构 参考孟岩老师的文章,对本文结构如下划分 基本数据类型基本语法数组和其他集合类基本输入输出和文件处理,输入...
    不抄完整本三国不改名阅读 552评论 0 1
  • 携思而习!属最高境界的学习! 白育荣老师感悟:今天听取了王晓春先生的个案诊疗课程,了解到个案诊疗就是对一个学生或一...
    刘宏教育蒲公英阅读 1,099评论 1 0
  • 我老了,不能再爱了 也许当时应该勇敢一点 在那个 豆蔻年华 我老了,不能再爱了 也许当时我很幸福 在那个 豆蔻年华...
    sugarMOMO阅读 324评论 1 1
  • “我能想到最浪漫的事,就是陪你一起慢慢变老。”——题记。 姥姥每次住院,姥爷都不跟着去,里外都是大姨张罗的。 办好...
    又开始想吃柚子了阅读 1,220评论 0 0