iOS key value coding kvc在接收json数据与 model封装中的使用
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:0 error:Nil]; //NSLog(@"%@",json); NSLog(@"completed"); NSDictionary *dataDic = [NSDictionary dictionaryWithDictionary:[[json objectForKey:@"subjects"] objectAtIndex:0]]; NSLog(@"dataDic = %@",dataDic); MovieModel *movie = [[MovieModel alloc]initWith:dataDic]; NSLog(@"%@",movie); }]; [request setFailedBlock:^{ NSLog(@"%@",[brRequest error]); }]; [request startAsynchronous];
3:请求处理的log结果
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。