Tool

KVC系列-字典转模型-代码示例

2018-09-17  本文已影响3人  codeTao

将后台JSON数据中的字典转成本地的模型,我们一般选用部分优秀的第三方框架,如JSONKit、MJExtension、YYModel等。但是,一些简单的数据,我们也可以尝试自己来实现转换的过程。

请求数据:

[
    {
        "id": "11111", 
        "imgUrlStr": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1537438673&di=3334d23c67c4150a8411dbea6c5b975f&imgtype=jpg&er=1&src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2F2015%2F761%2F700%2F2503007167_1330985815.search.jpg", 
        "nameStr": "指环王"
    }, 
    {
        "id": "22222", 
        "imgUrlStr": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536843778106&di=9c6fd0e12ffeee2962cf68f0ce69983e&imgtype=0&src=http%3A%2F%2Fi0.itc.cn%2F20140429%2F2d89_88d29539_57c8_8d7f_d58b_78384413fcc0_2.jpg", 
        "nameStr": "冰与火之歌"
    }, 
    {
        "id": "11111", 
        "imgUrlStr": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1537438673&di=3334d23c67c4150a8411dbea6c5b975f&imgtype=jpg&er=1&src=http%3A%2F%2Fcbu01.alicdn.com%2Fimg%2Fibank%2F2015%2F761%2F700%2F2503007167_1330985815.search.jpg", 
        "nameStr": "指环王"
    }, 
    {
        "id": "22222", 
        "imgUrlStr": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536843778106&di=9c6fd0e12ffeee2962cf68f0ce69983e&imgtype=0&src=http%3A%2F%2Fi0.itc.cn%2F20140429%2F2d89_88d29539_57c8_8d7f_d58b_78384413fcc0_2.jpg", 
        "nameStr": "冰与火之歌"
    }
]

下面我们使用KVC来实现下字典转模型:

1. 创建模型类

假设网络请求图片信息并在APP的界面上展示,这里新建一个图书模型,id表示图书的ID,imgUrl是图书的封面地址(可以用SDWebImage加载该图),nameStr时图书的名字。

我们建立一个模型如下(暂不先管id这个含有关键字的属性,后面会讲):

@interface SKBookModel : NSObject
//根据请求数据的字段名, 定义属性名
@property (nonatomic, copy) NSString *bookId;
@property (nonatomic, copy) NSString *imgUrlStr;
@property (nonatomic, copy) NSString *nameStr;

+ (instancetype)bookModelWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;

//加载plist文件, 字典转模型
+ (NSArray <SKBookModel *> *)bookModelsWithPlistName:(NSString *)plistName;
@end
#import "SKBookModel.h"
@implementation SKBookModel
+ (instancetype)bookModelWithDict:(NSDictionary *)dict {
    return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict {
    self = [super init];
    if (self) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}
@end
#import "SKBookModel.h"
@implementation SKBookModel
+ (instancetype)getSKBookModelWithDict:(NSDictionary *)dict {
    SKBookModel *bookModel = [[self alloc] init];
    [bookModel setValue:[dict valueForKey:@"id"] forKey:@"id"];
    [bookModel setValue:[dict valueForKey:@"imgUrlStr"] forKey:@"imgUrlStr"];
    [bookModel setValue:[dict valueForKey:@"nameStr"] forKey:@"nameStr"];

    return bookModel;
}
@end

2. 含有模型未定义属性同名字段的字典

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    //空的什么都不写都可以
}

3. 含有系统关键字同名字段的字典

注意: 最开始获取JSON数据里面有一个id的字段, 而id是iOS的一个关键字,不能用关键字定义属性名,此时我们就需要在model类中修改这个属性的名字,并在 - (void)setValue:(id)value forUndefinedKey:(NSString *)key 的方法体中重写该方法,以针对id字段作特殊处理。

@interface SKBookModel : NSObject
@property (nonatomic,strong) NSString *bookId;
@end
- (void)setValue:(id)value forUndefinedKey:(NSString *)key  {
    if([key isEqualToString:@"id"]){
        //self.bookId = value;//不推荐
        [self setValue:value forKey:@"bookId"]; // 推荐
    }
}

4. 数据通过自定义tableViewCell 展示

#import <UIKit/UIKit.h>
#import "SKBookModel.h"

@interface SKCell : UITableViewCell
@property (nonatomic, strong) SKBookModel *bookModel;
@end
@interface SKCell()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *bookID;
@property (weak, nonatomic) IBOutlet UILabel *bookName;
@end

@implementation SKCell
- (void)setBookModel:(SKBookModel *)bookModel{
    _bookModel = bookModel;

    self.bookID.text = bookModel.bookId;
    self.bookName.text = bookModel.nameStr;
    
    //self.iconView.image = [UIImage imageNamed:bookModel.imgUrlStr]; //UIImage获取本地图片
    
    //UIImage 获取网络图片
    NSURL *imageUrl = [NSURL URLWithString:bookModel.imgUrlStr];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
    self.iconView.image = image;
@end
}

5.获取数据, 使用KVC字典转模型

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
    SKCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.bookModel = self.modelArr[indexPath.row];  
    return cell;
}

6. 补充: - (void)setValue:(id)value forUndefinedKey:(NSString *)key方法的作用

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    //空的什么都不写都可以
    //return nil;
}
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    if ([key isEqualToString:@"id"]) {
        //self.id1 = value;// 不推荐
        [self setValue:value forKey:@"id1"]; // 推荐
    }
    if ([key isEqualToString:@"description"]) {
        //self.description1 = value;// 不推荐
        [self setValue:value forKey:@"description1"]; // 推荐
    }
}

使用图片:


The Lord of the Rings.jpeg A Song of Ice and Fire.jpeg

由于笔者水平有限,文中如果有错误的地方,或者有更好的方法,还望大神指出。
附上本文的所有 demo 下载链接,【GitHub】
如果你看完后觉得对你有所帮助,还望在 GitHub 上点个 star。赠人玫瑰,手有余香。

上一篇下一篇

猜你喜欢

热点阅读