Search code examples
objective-cpropertiesreleasedealloc

ObjC: can I use property = nil instead of self.property = nil to release it?


I have properties in the .h file and synthesized in .m file, I know I can release it by using:

self.property = nil;

but can I use:

property = nil;

instead?

Thanks!


Solution

  • No. This is because the @synthesized methods that are generated using the retain option (or strong, if you're use ARC) actually look something like this:

    - (void)setValue:(NSString *)newValue {
        [value autorelease];
        value = [newValue retain];
    }
    

    Therefore, when you do self.property = nil, the old value will be autoreleased, and the nil will be retained, which does nothing at all anyway.

    When you just do iVar = nil, you never release the object the variable previously contained, so you leak.

    Of course, if you're using ARC (Automatic Reference Counting), you don't have to worry about any of this. The compiler will do the work for you. In that case, iVar = nil will have the exact same effect as self.iVar = nil, though some might see it as less clear.