C层:
发一个请求:(告诉M 要做什么)
- (void)reload:(__unusedid)sender {
self.navigationItem.rightBarButtonItem.enabled = NO;
NSURLSessionTask *task = [PostglobalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
if (!error) {
self.posts = posts;
[self.tableViewreloadData];
}
}];
[UIAlertViewshowAlertViewForTaskWithErrorOnCompletion:task delegate:nil];
[self.refreshControlsetRefreshingWithStateOfTask:task];
}
M 做完之手,产生多个post对象,放到self.post数组里面。C拿到M给的post对象,去更新V
cell.post = [self.postsobjectAtIndex:(NSUInteger)indexPath.row];
M层:
M 收到C的请求:去请求数据,解析,转换成post对象,然后通过block返回给C
+ (NSURLSessionDataTask *)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block {
return [[AFAppDotNetAPIClientsharedClient] GET:@"stream/0/posts/stream/global"parameters:nilsuccess:^(NSURLSessionDataTask * __unused task, id JSON) {
NSArray *postsFromResponse = [JSON valueForKeyPath:@"data"];
NSMutableArray *mutablePosts = [NSMutableArrayarrayWithCapacity:[postsFromResponse count]];
for (NSDictionary *attributes in postsFromResponse) {
Post *post = [[Postalloc] initWithAttributes:attributes];
[mutablePosts addObject:post];
}
if (block) {
block([NSArrayarrayWithArray:mutablePosts], nil);
}
} failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
if (block) {
block([NSArrayarray], error);
}
}];
}
V层:
V:拿到C给的数据,来展示出来,这一步就是更新UI
- (void)setPost:(Post *)post {
_post = post;
self.textLabel.text = _post.user.username;
self.detailTextLabel.text = _post.text;
[self.imageViewsetImageWithURL:_post.user.avatarImageURLplaceholderImage:[UIImageimageNamed:@"profile-image-placeholder"]];
[selfsetNeedsLayout];
}
其中 :
[self.imageViewsetImageWithURL:_post.user.avatarImageURLplaceholderImage:[UIImageimageNamed:@"profile-image-placeholder"]];
这句代码是对UIImageView的扩展,在UIKit+AFNetworking可以直接使用,非常方便。