创建Movie的model
@property (nonatomic, copy) NSString *movieId;
@property (nonatomic, copy) NSString *movieName;
@property (nonatomic, copy) NSString *pic_url;
@property (nonatomic, retain) UIImage *imageData; // 图片数据
#pragma mark - 重写pic_url的setter方法
- (void)setPic_url:(NSString *)pic_url
{
if (_pic_url != pic_url) {
[_pic_url release];
_pic_url = [pic_url copy];
__block Movie *weakSelf = self;
// 当前模型对象有了图片网址之后,立即发起网络请求,获取图片数据
[ImageDownloader imageDownloaderWithURLStr:pic_url result:^(UIImage *image) {
weakSelf.imageData = image;
}];
}
}
MovieTableviewController
@property (nonatomic, retain) NSMutableArray *allDataArray;
- (void)loadData
{
self.allDataArray = [NSMutableArray array];
__block MovieTableViewController *weakSelf = self;
NSURL *url = [NSURL URLWithString:kMovieList];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// 3. 拆解数据,转为方便使用的模型
for (NSDictionary *item in dict[@"result"]) {
Movie *movie = [Movie new];
[movie setValuesForKeysWithDictionary:item];
[_allDataArray addObject:movie];
}
// NSLog(@"%@", _allDataArray);
// 4. 刷新页面
[weakSelf.tableView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _allDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Movie" forIndexPath:indexPath];
// 取出要显示的模型
Movie *m = _allDataArray[indexPath.row];
cell.textLabel.text = m.movieName;
// 设置图片
if (m.imageData == nil) {
// 如果当前模型没有图片,就添加观察者,观察当前模型的imageData属性,如果imageData属性有值了,就重新显示当前cell
// 观察谁,就给谁发消息
[m addObserver:self // 观察者
forKeyPath:@"imageData" // 被观察的属性名称
options:NSKeyValueObservingOptionNew // 观察的时新值
context:indexPath]; // 传递当前被观察模型所属的cell的标识
} else {
// 有图片
cell.imageView.image = m.imageData;
}
return cell;
}
#pragma mark 观察者发现情况后执行的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// 1. 获取indexPath
NSIndexPath *indexPath = (NSIndexPath *)context;
// 2. 获取图片
UIImage *newImage = change[@"new"];
// 3. 获取当前行
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
// 4. 将图片显示
cell.imageView.image = newImage;
// 5. 刷新当前行
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// 6. 移除观察者
[object removeObserver:self forKeyPath:keyPath context:context];
}