iOS key value coding kvc在接收json数据与 model封装中的使用

时间:2021-11-24 20:51:26

iOS key value coding  kvc在接收json数据与 model封装中的使用

使用 kvc 能够极大的简化代码工作,及以后的接口维护工作;

1:先创建MovieModel类.h和 .m

注意Model类的属性根据 后台接口返回的 json数据 里面的字段对应,一一对应;

//  Created by cocoajin on 14-1-15.
// Copyright (c) 2014年 www.zhgu.net. All rights reserved.
// #import <Foundation/Foundation.h> @interface MovieModel : NSObject @property (nonatomic,strong)NSString *alt;
@property (nonatomic,strong)NSNumber *collect_count;
@property (nonatomic,strong)NSString *original_title;
@property (nonatomic,strong)NSString *title;
@property (nonatomic,strong)NSNumber *year;
@property (nonatomic,strong)NSString *subtype;
@property (nonatomic,strong)NSNumber *id;
@property (nonatomic,strong)NSDictionary *images;
@property (nonatomic,strong)NSDictionary *rating; - (id)initWith:(NSDictionary *)aDic; @end
#import "MovieModel.h"

@implementation MovieModel

- (id)initWith:(NSDictionary *)aDic
{
self = [super init]; if (self) {
[self setValuesForKeysWithDictionary:aDic];
} return self;
} - (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
NSLog(@"未定义的key:%@",key);
} - (NSString *)description
{
return [NSString stringWithFormat:@"thie movie is :alt=%@ ,collect_count=%@ ,original_title=%@ ,title=%@ ,year=%@ ,subtype=%@, id=%@ ,image=%@ ,rating=%@",self.alt,self.collect_count,self.original_title,self.title,self.year,self.subtype,self.id,self.images,self.rating];
}

2:接口请求处理部分:

    NSString *douBanApi = @"http://api.douban.com/v2/movie/top250?count=5";
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:douBanApi]]; __block ASIHTTPRequest *brRequest = request; [request setCompletionBlock:^{
id json = [NSJSONSerialization JSONObjectWithData:[brRequest responseData] options: error:Nil];
//NSLog(@"%@",json);
NSLog(@"completed"); NSDictionary *dataDic = [NSDictionary dictionaryWithDictionary:[[json objectForKey:@"subjects"] objectAtIndex:]];
NSLog(@"dataDic = %@",dataDic); MovieModel *movie = [[MovieModel alloc]initWith:dataDic];
NSLog(@"%@",movie); }]; [request setFailedBlock:^{
NSLog(@"%@",[brRequest error]);
}]; [request startAsynchronous];

3:请求处理的log结果

iOS key value coding  kvc在接收json数据与 model封装中的使用