OGeek|极客世界-中国程序员成长平台

标题: ios - 无法在带有 block 的 UITableViewCell 中设置 UIButton 标题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:55
标题: ios - 无法在带有 block 的 UITableViewCell 中设置 UIButton 标题

我在自定义 UITableViewCell 中有一个 UIButton,当我按下按钮时,它会使用 AFNetworking 将数据发布到我的服务器,在成功 block 我设置了一个新的按钮标题,但它不起作用。 在 CutomTableViewCell 中,我使用了一个协议(protocol),所以我可以响应按钮点击:

@implementation SubjectReplyCell

- (IBAction)btnReplyPressedUIButton *)sender {

    if (self.delegate && [self.delegate respondsToSelectorselector(postData:atIndex]) {
        [self.delegate postData:self atIndex:sender.tag];
    }
}
@end

然后我实现委托(delegate)并将数据发布到服务器:

@implementation BBSDetailsController
- (void)postDataSubjectReplyCell *)cell atIndexNSInteger)idx {
    urlString = [API_HOST stringByAppendingString:BBS_PRAISE_OPPOSITION];
    __weak typeof(SubjectReplyCell) *weakCell = cell;

    [requestManager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"returnode"] isEqualToString"success"]) {
            //it doesn't work
            [weakCell.btnReply setTitle"newTitle" forState:UIControlStateNormal];
            [weakCell setNeedsLayout];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}

但是,如果我将标题设置在 block 之外,它会很好地工作:

- (void)postDataSubjectReplyCell *)cell atIndexNSInteger)idx {
    urlString = [API_HOST stringByAppendingString:BBS_PRAISE_OPPOSITION];

    //it work
    [cell.btnReply setTitle"newTitle" forState:UIControlStateNormal];

    [requestManager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"returnode"] isEqualToString"success"]) {

        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}



Best Answer-推荐答案


AFNetworking 默认使用主队列来处理失败和完成 block ,因此您无需担心自己为 UI 更改调用主线程。 See this answer

如果要修改 block 内的对象,则需要使用 __block 关键字(即两个下划线)。使用 __block 会提前告诉编译器您计划改变 block 内的对象,因此请以不同的方式处理该对象以保留更改。

所以这个:

__weak typeof(SubjectReplyCell) *weakCell = cell;

应该是这样的:

__block typeof(SubjectReplyCell) *weakCell = cell;

编辑: 您不需要在您的单元格上使用 __weak ,因为在此 block 中修改您的单元格不应创建引用循环。在这种情况下,您的单元格将保留在完成 block 中,但单元格本身并不保留 block ,因此这两个不会创建保留循环。

你需要使用 __weak 如果两个正在运行的对象有可能导致一个保留循环,比如当你在一个 block 中捕获 self 并且该 block 也被 self 捕获时。 Here's another answer for some more clarity

关于ios - 无法在带有 block 的 UITableViewCell 中设置 UIButton 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31705079/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4