1

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 .

user5465320
  • 719
  • 2
  • 7
  • 15

1 Answers1

3

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
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • In my opinion , you are wrong . 1、If create a property , the ivar's status will not be private . 2、in block ,we can not use self , the 'self' pointer is a strong pointer – user5465320 Oct 20 '15 at 06:39
  • 1
    No, the property is private. It's defined in the private class extension. And there's nothing wrong with a strong reference to self in this case. There is no reference cycle. Try it. – rmaddy Oct 20 '15 at 06:46
  • They don't have to use a property -- they can use an ivar if they want; though I agree that the ivar should be declared in the extension or implementation and not in the interface. – newacct Oct 21 '15 at 06:21
  • @newacct Yes, you can access the ivar using the "strong" `self`. But you can't access an ivar through a "weak" `self`. I suggested the property due to the original use of the "weak" `self`. Then I realized the code didn't need the weak pointer at all. – rmaddy Oct 21 '15 at 15:32