博客> 数据解析及model封装
数据解析及model封装
2018-12-11 03:55 评论:0 阅读:735 syfuxi
ios 封装 数据解析

我们常常需要对数据进行解析,并且建立model存放数据,今天总结一下具体操作以及它们的封装。

1.数据解析并封装

建立一个文件用来进行数据解析。

.h文件

#import <Foundation>

@interface DataService : NSObject

//加载

+(id) loadDataWithListName:(NSString *)listName;

@end

.m文件

#import "DataService.h"

@implementation DataService

+(id)loadDataWithListName:(NSString *)listName {

//获取文件
NSString *path = [[NSBundle mainBundle] pathForResource:listName ofType:@"json"];

//读取
NSData *jsonData = [NSData dataWithContentsOfFile:path];

//json---&gt;data
id data = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

return data;
}

@end

2.model的封装

相比于数据解析的封装,model的封装要相对复杂一点,它的思路是首先要找到映射的字典(要找到key属性的对应关系,json中的key和model类的属性名会形成一个映射关系),然后获取到子类的属性名字,找到set方法,最后进行赋值。

具体实现代码如下:

 .h文件

#import <Foundation>

@interface BaseModel : NSObject

- (void) setvalueForAttributesWithDictionary:(NSDictionary *)keyedValues;

@end

.m文件

#import "BaseModel.h"

@implementation BaseModel

/**
转换方法:
 allKeys---&gt;title----&gt;setTitle(字符串)---&gt;setTitle(方法)

*/

- (NSMutableDictionary *)_bulidRalationShip:(NSDictionary *)dic {

NSArray *allkeys = [dic allKeys];

NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];

for (NSString *key in allkeys) {

    if ([key isEqualToString:@"id"]) {

        //获取该类的字符串
        NSString *className = NSStringFromClass([self class]);
        //创建一个string名字
        NSString *newString = [NSString stringWithFormat:@"%@id", className];
        //将新的string用来做model中的属性名,这里id要注意,不能直接用来做属性名,因为他是关键字
        [mutableDic setObject:newString forKey:@"id"];

    } else {

        //直接将key名字作为model的属性名
        [mutableDic setObject:key forKey:key];
    }
}

return mutableDic;
}

//创建一个字符串拼接方法
- (SEL)_findSetterMethod:(NSString *)name {

//1.取首字母
NSString *firstLetter = [[name substringFromIndex:1] uppercaseString];

//2.截取剩下的字母
NSString *lastLetter = [name substringFromIndex:1];

//3.拼接
NSString *setterName = [NSString stringWithFormat:@"set%@%@:", firstLetter, lastLetter];

//4.SEL
//从一个方法产生字符串
SEL setter = NSSelectorFromString(setterName);

return setter;
}

//创建一个带字典的属性方法
- (void) setvalueForAttributesWithDictionary:(NSDictionary *)keyedValues {

     //1.获取到映射字典
     NSMutableDictionary *relationShipDic = [self _bulidRalationShip:keyedValues];

     //2.找到set方法
     NSArray *allkeys = [relationShipDic allKeys];

     for (NSString *key in allkeys) {

    NSString *propertName = [relationShipDic objectForKey:key];
    SEL method = [self _findSetterMethod:propertName];

    //3.赋值
    id value = [keyedValues objectForKey:key];

    //判断该方法是否能够是吸纳
    if ([self respondsToSelector:method]) {

        [self performSelector:method withObject:value];
    }

 }
}
收藏
0
sina weixin mail 回到顶部