您的位置:首页 > 产品设计 > UI/UE

UI_model传值, json数据解析

2015-08-17 21:10 399 查看
model 传值

首先建一个作为model的类, 继承于NSObject

接口文件写属性 , 实现文件里写属性的释放和一个 容错方法 (KVC)

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{

}


如果请求图片的网络地址, 需要在工程里添加一个SDWebImage的第三方, 并引头文件 #import”UIImageView + WebCache ”

-请求方法如下:

[承接图片的视图 sd_setImageWithURL:[NSURL URLWithString:图片地址]


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

豆瓣电影 , 电影界面



先写一个model 类 , 有2条属性 , 用来传值

//  movie.h 文件
@property(nonatomic, copy)NSString *movieName; // 电影名
@property(nonatomic, copy)NSString *pic_url;  // 图片

// movie.m 文件

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
// KVC 容错方法
}

- (void)dealloc
{
[_movieId release];
[_movieName release];
[super dealloc];
}


在视图控制器里铺一个tableView, 进行基本设置 , 然后进行解析, 主要代码如下

使用本地movieList.txt文档 进行数据解析

NSString *path = [NSBundle
mainBundle]pathForResource@"movie list"  ofType@"txt"];
NSData *data = [NSData dataWithContentOffile:path]
//  json 解析
NSMutableDictionary *dic = [NSJSONSerialization
options:NSJSONReadingMutableContainers error:nil];
for (NSMutableDictionary *temp in dic[@"result"]) {
Movie *mov = [[Movie alloc]init];
[mov setValuesForKeysWithDictionary:temp];
[self.movieArr addObject:mov];
[mov release];
}


请求网络数据, 进行数据解析

NSString *strURL = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php";

NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

// 异步get请求 (block 方式)
[NSURLConnection sendAsynchronousRequest:request
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 对data进行数据处理
//json 解析
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers error:nil];
for (NSMutableDictionary *temp in dic[@"result"]) {
Movie *mov = [[Movie alloc]init];
[mov setValuesForKeysWithDictionary:temp];
[self.movieArr addObject:mov];
[mov release];
}
[self.movieTableView reloadData];
}];


显示数据

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return  self.movieArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *reuse = @"reuse";
UITableViewCell *cell = [tableView
dequeueReusableHeaderFooterViewWithIdentifier:reuse];
if (!cell) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:reuse] autorelease];
}
Movie *movie = self.movieArr[indexPath.row];
cell.textLabel.text = movie.movieName;
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:movie.pic_url];

return  cell;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: