2

In a lot of question it is asked if its ok to use self in blocks. The answer is no, to avoid retain cycle.

Now when i use an "ivar" in my block in my UIViewController it should be fine. But when i use:

- (void)viewDidLoad
{
    [_customCell setChangedValueBlock:^{
        if(_object != nil){
            NSLog(@"This is a sample");
        }
    }];
}

The dealloc method never called:

-(void)dealloc{
    NSLog(@"Dealloc");
}

When i remove the if(_object != nil){, the dealloc method is called.

Should i make weak reference to the _object before passing it to the block?

Tulon
  • 4,011
  • 6
  • 36
  • 56
Oritm
  • 2,113
  • 2
  • 25
  • 40

1 Answers1

5

Using an ivar (property, whatever) is exactly like using self - you have implicitly used self. You need to do the weak-strong dance.

It would be much better to pass thru a property, though, because it can be made thread-safe and because accessing an instance variable directly on a released weak reference will cause your device to explode.

Community
  • 1
  • 1
matt
  • 515,959
  • 87
  • 875
  • 1,141