Search code examples
objective-cxcodenulldealloc

Why does setting self.object to nil cause a crash


In the following scenario I get a crash

    if (self.videoEngine != nil)
{
    [self.videoEngine.player.view removeFromSuperview];

    [videoEngine release];
    self.videoEngine = nil;
}

The videoEngine object is (nonatomic, retain), and it is synthesized using videoEngine = _videoEngine. If I remove the self.videoEngine = nil line the code works properly. Is this correct behaviour, and why does the nil line cause a crash? Would the self.videoEngine = nil still cause an issue within the viewDidUnload function?


Solution

  • You should only release _videoEngine because that is the the synthesized name. videEngine is only the name of the setter and getter, but the value is stored in the syntheseized name. So your code should be:

        if (self.videoEngine != nil)
    {
        [self.videoEngine.player.view removeFromSuperview];
    
        [_videoEngine release];
        self.videoEngine = nil;   // Unnecessary
    

    }

    But you don´t need to call self.videEngine = nil after releasing the _videEngine because the setter will always return nil.

    It is not considered a proper method of releasing by calling the setter method with nil, although it works, like is done with the line: self.videoEngine = nil; // Unnecessary. The proper way of releasing is only [_videoEngine release];