【问题标题】:Strong & weak inside a block. How can I approach this issue?块内的强弱。我该如何解决这个问题?
【发布时间】:2015-07-31 17:17:38
【问题描述】:

我有一个表格视图,与 stackoverflow 非常相似,用户可以选择最佳答案。

我有一个 *answerContainers 的 NSMutableArray,其中包含一个 Answer 对象。

假设问题有 10 个答案。提出问题的用户选择第 3 个答案作为最佳答案。

我发出一个调用,将答案标记为服务器上的最佳答案,结果是更新的 Answer 对象,我想在我的完成块中对其进行操作。

所以它看起来像这样......

- (void)selectBestAnswer {
    for (AnswerContainer *answerContainer in self.answerContainers) {
        if (answerContainer.selected) { //can only be 1 selected
            Answer *answer = answerContainer.answer;
            QuestionDetailTableViewController * __weak weakSelf = self;
            [answer markAsBestAnswer:^(BOOL success, id responseObject, NSInteger statusCode, NSArray *messages, NSArray *errors) {
                if (success) {
                    QuestionDetailTableViewController *strongSelf = weakSelf;
                    Answer *answer = [Answer instanceFromDictionary:responseObject];

                    [strongSelf replaceAnswerWithAnswer:answer];

                    [strongSelf reloadTableView];
                }
            }];
        }
    }
}

这是我的问题

1) 我是否应该像这样让我的弱者成为整个控制器。还是您通常只为了回答容器而这样做?

【问题讨论】:

  • 为什么你要声明一个weak变量weakAnswerContainer?以后不用了,有什么用?你甚至知道你为什么这样做吗? weakSelf 是从哪里来的?你的代码没有意义。
  • 您将 self 作为 AnswerContainer,将 weakSelf 作为 QuestionDetailTableViewController。这个方法属于什么类?
  • @MikeAtNobel 哎呀。当我将代码复制到问题中时,正在切换代码中的某些内容。我现在将两种类型固定为相同。
  • 对self的引用是控制器。据我所知,它与 AnswerContainer 无关。检查此link 以了解何时应该使用弱修饰符。
  • @TommieC。类名上有一个类型,现在已修复。

标签: ios objective-c objective-c-blocks weak-references


【解决方案1】:

扔掉所有“弱”的东西。只有在块保留selfself 保留块的非常特殊的情况下才需要它,从而导致保留循环,从而导致self 稍后泄漏。你不是那种情况,所以根本不要使用“弱强舞”。

【讨论】:

  • 我什么时候会遇到这种情况?仅当我对该块有实际的强引用时,例如@property MyCompletionBlock completionBlock?然后是我的完成块代码,引用self?
  • 基本上是的。但是请参阅我已经给您的关于我的书链接的讨论:它描述了一些可能出现这种情况的令人惊讶的情况。
【解决方案2】:

如果你只有一个选择的答案,为什么不- (void)bestAnswerSelected:(Answer *)answer

- (void)sendAndUpdateBestAnswer:(Answer *)answer {
        [answer markAsBestAnswer:^(BOOL success, id responseObject, NSInteger statusCode, NSArray *messages, NSArray *errors) {
            if (success) {

                Answer *answer = [Answer instanceFromDictionary:responseObject];

                [self replaceAnswerWithAnswer:answer];

                [self reloadTableView];
            }
        }];
}

我猜selectBestAnswer是ins

【讨论】:

    猜你喜欢
    • 2022-10-19
    • 2020-03-25
    • 2020-02-14
    • 2021-10-23
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多