Search code examples
iospointersblocklifecycleweak

iOS : instance variable in block


My Object have some instance variable , like this:

@interface MyObject : NSObject 
{
@private 
    NSDictionary * resultDictionary ;
}

this is the method :

- (void) doSomething
{
    __weak typeof(self) weakSelf = self ;

    [TaskAction invoke:^(NSDictionary* result){
        if(result){
            weakSelf->resultDictionary = result ; // dereferencing a weak pointer is not allowed due to possible null value caused by race condition , assign it to strong variable first ...
        }
    }]
}

the iOS compiler throw a Error : // dereferencing a weak pointer is not allowed due to possible null value caused by race condition , assign it to strong variable first ...

the error statement is :weakSelf->resultDictionary = result ;

Could you help me that why the mistake .


Solution

  • You actually have no need for the weak reference in this code. There is no risk of a retain cycle here.

    However, if you did, the solution would be to make a property for the private ivar. Then you could access the property via the weak pointer inside the block.

    Side note - don't put private ivars in the public interface. There is no good reason to put private details in the public interface. Put the private ivar (or the private property) in the private class extension in the .m file.

    .h file:

    @interface MyObject : NSObject
    @end
    

    .m file:

    @interface MyObject()
    
    @property (nonatomic, strong) NSDictionary *resultDictionary;
    @end
    
    @implementation MyObject
    
    - (void)doSomething {
        [TaskAction invoke:^(NSDictionary* result){
            if (result){
                self.resultDictionary = result;
            }
        }];
    }
    
    @end