[英]can't set UIButton title in UITableViewCell with block
我在自定義UITableViewCell
有一個UIButton
,當我按下按鈕時,它會使用AFNetworking
將數據發布到我的服務器,在成功塊中我設置了一個新的按鈕標題,但它不起作用。 在CutomTableViewCell
我使用了一個協議,所以我可以響應按鈕點擊:
@implementation SubjectReplyCell
- (IBAction)btnReplyPressed:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:@selector(postData:atIndex:)]) {
[self.delegate postData:self atIndex:sender.tag];
}
}
@end
然后我實現委托並將數據發布到服務器:
@implementation BBSDetailsController
- (void)postData:(SubjectReplyCell *)cell atIndex:(NSInteger)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) {
}];
}
但是,如果我將標題設置在塊之外,則效果很好:
- (void)postData:(SubjectReplyCell *)cell atIndex:(NSInteger)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) {
}];
}
AFNetworking 默認使用主隊列來處理失敗和完成塊,因此您無需擔心自己調用主線程來進行 UI 更改。 看到這個答案
如果要修改塊內的對象,則需要使用__block
關鍵字(即兩個下划線)。 使用__block
提前告訴編譯器您計划改變塊內的對象,因此請區別對待此對象以保留更改。
所以這:
__weak typeof(SubjectReplyCell) *weakCell = cell;
應該是這樣的:
__block typeof(SubjectReplyCell) *weakCell = cell;
編輯:您不需要在單元格上使用__weak
,因為在此塊中修改單元格不應創建參考循環。 在這種情況下,您的單元格將保留在完成塊中,但單元格不會同時保留塊本身,因此這兩個不會創建保留循環。
如果游戲中的兩個對象有可能導致保留循環,則需要使用__weak
,例如當您在塊中捕獲 self 並且該塊也被 self 捕獲時。 這是另一個更清晰的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.