4

In some code I sometimes see this:

@property (nonatomic, assign) NSObject *foo;

...

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

Is it really necessary to nil an object when it hasn't been retained? Won't this actually cause problems?

3 Answers 3

3

It is good practice to set any pointer you are no longer interested in to nil. I don't advocate the use of accessors like this in -dealloc because of possible accessor side effects (like posting notifications or KVOs), but that's a controversial position and Apple is not consistent in their own code. In any case, it is good practice to nil your pointers. It certainly will not cause problems, and the habit of nil-ing your pointers in -dealloc will save you significant bugs in the future.

In this specific case it may not be necessary, but what kind of problem are you suggesting?

2
  • 1
    I just was wondering if it was needed, so I could avoid unknown bugs and many a headache. One thing I'm confused about is how variables are assigned. I thought that when I assign self.foo to nil, wouldn't the other hypothetical variable that is assigned to it be set to nil as well? I'm having a hard time explaining my problem, so please let me know if you understand :)
    – Meroon
    Jul 22, 2009 at 3:50
  • 1
    The instance variable foo (which we presume backs self.foo in this case, but we can't know from this code) is a pointer to an object. When you set it to nil, you are moving the pointer, not changing the object (or any other pointers that point to that object). You are right to try to avoid future headaches and bugs, which is why you should be in the habit of setting all your ivar pointers to nil in dealloc (as well as releasing any that you've retained).
    – Rob Napier
    Jul 22, 2009 at 4:26
3

A assign property does not have to have its ivar set to nil in -dealloc.

Setting the ivar to nil in -dealloc is harmless. Using the public accessor to set the property to nil in dealloc (either [self setFoo: nil] or self.foo = nil) may have unwanted side effects.

2

Assuming it's a synthesized accessor, there's no point to doing it in dealloc. Earlier, you might nil it out if you don't want to talk to the object anymore. I can't see how it would cause problems, though.

If it's not a synthesized accessor, the setter might also affect the inverse relationship in some way, and in that case it might be necessary to set it to nil in order to tell foo you're not going to be around anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.