关于AFNetworking 的一点疑问。

tangyumeng 发布于 2013年08月18日
无人欣赏。

关于AFNetworking sdk中的demo有一段代码中的疑问。 我之前处理网络请求的逻辑是:假如A push到 B。 B中开始网络请求,在未返回结果时pop出是是直接cancel掉网络请求的。(之前使用的是ASI) 这段时间看AFN时,demo中有段代码

- (void)reload:(id)sender {
[Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
    if (error) {
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil] show];
    } else {
        _posts = posts;
        [self.tableView reloadData];
    }
}];

}

我看代码中是把每个网络请求放在全局的queue中,因此pop时并没有cancel掉网络请求。但是在pop以后,B中的tableview已经不存在了,通过block的方式给tableview的数据源赋值,并且不会出现问题。是因为block中会抓取一份tableview么?或者应该怎样理解。。。

共3条回复
sycx 回复于 2013年08月18日

block 本身会对用到的对象 retain, 所以你这段代码,pop后,B和B中的tableview还会继续存在,直到block调用完毕,B才会被释放。

sipdar 回复于 2013年08月18日

可以用

- (void)reload:(id)sender {
__weak B weakSelf = self;
[Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
    if (error) {
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil] show];
    } else {
        _posts = posts;
        [weakSelf.tableView reloadData];
    }
}];
tangyumeng 回复于 2013年08月19日

多谢两位的解答。。。d

登录 或者 注册
相关帖子