您的位置:首页 > 其它

BaseModel

2016-01-06 21:09 239 查看
使用时 直接在需要 model 数据的地方写上和数据名相对应的属性 就可以解析到 model 中了

#import <Foundation/Foundation.h>

@interface BaseModel : NSObject

// 初始化方法   传入解析的json数据
- (id)initWithContentDic:(NSDictionary *)jsonDic;

// 属性名的映射字典 @{jsonDic.key  :  model.attringbute}
@property (nonatomic, copy)NSDictionary *mapDic;

@end


#import "BaseModel.h"

@implementation BaseModel

- (id)initWithContentDic:(NSDictionary *)jsonDic {

if (self  = [super init]) {

[self setAttributesWithDic:jsonDic];

}

return self;
}

- (void)setAttributesWithDic:(NSDictionary *)jsonDic {

#pragma mark--- 普通字符的赋值
//1. 将jsonDic中的所有的key值  转换成set方法
for (NSString *key in [jsonDic allKeys]) {

// 对key之进行操作  --> setKey:
NSString *bigan = [[key substringToIndex:1] uppercaseString];// 获取key值的首字母并大写
NSString *end = [key substringFromIndex:1]; // 获取key值除首字母外的其他字符

// 获取最后的set方法名
NSString *mothodString = [NSString stringWithFormat:@"set%@%@:",bigan,end];

// 将方法名转换成set方法
SEL mothod = NSSelectorFromString(mothodString);

// 2. 判断model类是否相应set方法,如果是的话 调用set方法并赋值
if ([self respondsToSelector:mothod]) {

// 获取需要保存的数据
id value = [jsonDic objectForKey:key];

//  确定value不为空
if (![value isKindOfClass:[NSNull class]]) {

// 调用set方法并赋值
[self performSelector:mothod withObject:value];
}
}

}

#pragma mark--- 特殊字符的赋值
for (NSString *key in self.mapDic) {

// 获取model对象中的特殊字符的属性名
NSString *attribute = [self.mapDic objectForKey:key];

// 对key之进行操作  --> setKey:
NSString *bigan = [[attribute substringToIndex:1] uppercaseString];// 获取key值的首字母并大写
NSString *end = [attribute substringFromIndex:1]; // 获取key值除首字母外的其他字符

// 获取最后的set方法名
NSString *mothodString = [NSString stringWithFormat:@"set%@%@:",bigan,end];

// 将方法名转换成set方法
SEL mothod = NSSelectorFromString(mothodString);

// 2. 判断model类是否相应set方法,如果是的话 调用set方法并赋值
if ([self respondsToSelector:mothod]) {

// 获取需要保存的数据
id value = [jsonDic objectForKey:key];

//  确定value不为空
if (![value isKindOfClass:[NSNull class]]) {

// 调用set方法并赋值
[self performSelector:mothod withObject:value];
}
}

}

}

@end


补充:使用 GCD创建一个 BaseModel 提高效率

dispatch_apply([jsonDic allKeys].count, dispatch_get_global_queue(0, 0), ^(size_t index) {
NSLog(@"%@dddddddddddddddddddd",[NSThread currentThread]);
NSString *key=[jsonDic allKeys][index];
// 对key之进行操作  --> setKey:
NSString *bigan = [[key substringToIndex:1] uppercaseString];// 获取key值的首字母并大写
NSString *end = [key substringFromIndex:1]; // 获取key值除首字母外的其他字符

// 获取最后的set方法名
NSString *mothodString = [NSString stringWithFormat:@"set%@%@:",bigan,end];

// 将方法名转换成set方法
SEL mothod = NSSelectorFromString(mothodString);

// 2. 判断model类是否相应set方法,如果是的话 调用set方法并赋值
if ([self respondsToSelector:mothod]) {

// 获取需要保存的数据
id value = [jsonDic objectForKey:key];

//  确定value不为空
if (![value isKindOfClass:[NSNull class]]) {

// 调用set方法并赋值
[self performSelector:mothod withObject:value];
}
}

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: