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
View Code
复制代码
复制代码
#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];
}
View Code
复制代码

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];
View Code
复制代码

3:请求处理的log结果

posted @   cocoajin  阅读(1108)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示