Why shouldn’t I use Objective C 2.0 accessors in init/dealloc? [closed]

It’s basically a guideline to minimize the potential for bugs.

In this case there is the (possibility) that your setter/getter may inadvertently make direct or indirect assumptions about the state of the object. These assumptions could be a problem when the object is in the midst of being setup or destroyed.

For example in the code below the observer does not know that ‘Example’ is being destroyed and could assume that other properties, which have already been freed, are valid.

(You could argue that your object should remove all observers before tearing itself down, which would be good practice, and another guideline to prevent inadvertent problems).

@implementation Example

-(void) setFoo:(Foo*)foo
{
   _foo = foo;
  [_observer onPropertyChange:self object:foo];
}

-(void) dealloc
{
   ...
   self.foo = nil;
}

@end

Leave a Comment