chris P
chris P

Reputation: 6589

Strong & weak inside a block. How can I approach this issue?

I have a tableview, where much like stackoverflow, a user can select an answer as being the best.

I have an NSMutableArray of *answerContainers, which contain an Answer object.

Let's say the question has 10 answers. The user who asked the question choose the 3rd answer as the best.

I fire off a call to mark the answer as the best on the server, and the result is the updated Answer object, which I want to manipulate in my completion block.

So it looks something like this...

- (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];
                }
            }];
        }
    }
}

Here are my questions

1) Should I make my weak self of the entire controller, like this. Or do you typically only do this for say the answerContainer?

Upvotes: 0

Views: 70

Answers (2)

matt
matt

Reputation: 534958

Just throw all the "weak" stuff away. It is needed only in the very special situation where a block retains self and self retains the block, thus causing a retain cycle which makes self leak later on. You are not in that situation so don't use the "weak-strong dance" at all.

Upvotes: 2

Klevison
Klevison

Reputation: 3484

If you have only one selected answer, why not - (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];
            }
        }];
}

I presume that selectBestAnswer is ins

Upvotes: 0

Related Questions