0
votes

With the recent XCode update some code blocks are displaying as warnings where "Block implicitly retains 'self'"

It is my understanding that the when you create blocks it is best practice to create a weak self to keep from creating a strong reference that will not be garbage collected.

In the below example I set the myArray to self->myArray as recommended by XCode. Does this create the strong reference? Why can't I use 'weakSelf->myArray`? Attempting to do so results in this error:

Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to strong variable first

I thought the whole point was to create weak refrences? Isn't weakSelf just a pointer to self?

Is the self-> even necessary in the below instance?

@interface SomeViewController (){
    NSMutableArray * myArray;
}
@end


- (void) doSomethingInBackground {
    // Do NSURLSessionTask on the background and onCompletion call mySuccessBlock.
}



- (SomeBlock) mySuccessBlock {

    __block __typeof__(SomeViewController) __weak * weakSelf = self;

    return ^(NSDictionary* result){

//this line is my related to my question
        self->myArray = [weakSelf sortResultsAlphabetically: result];

        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData]
        });

    };
}

Would recasting to be the correct way?

SomeViewController * strongSelf = weakSelf;
strongSelf->myArray = [weakSelf sortResultsAlphabetically: result];
1

1 Answers

2
votes

The error message is right. You have to do the "weak-strong dance". You are only doing half of the dance. Pass self into the block as weak, but then immediately assign it, inside the block, to a strong reference (as in your edited "Would recasting to be the correct way?").