Search code examples
iphoneobjective-cmemory-managementgarbage-collectiondealloc

Objective-C: Do you have to dealloc property objects before deallocating the parent object?


Let's say I have an object named "foo" with another object named "bar" as property.

When "foo" deallocates, will it automatically remove all references to "bar" so that "bar" deallocates as well? or will "foo" deallocate and "bar" float in memory somewhere? even if all of "bar"'s references are defined in "foo".

thanks in advance.


Solution

  • If the foo object has any retains on or copies of (thanks Dave) bar, for example when you declare the property as either one of these:

    @property (nonatomic, retain) NSString *bar;
    // Or
    @property (nonatomic, copy) NSString *bar;
    

    You'll need to release bar when you deallocate foo:

    - (void)dealloc
    {
        [bar release];
    
        [super dealloc];
    }
    

    The system won't free bar's memory space for you until you get rid of all references to it (i.e. reference count goes down to 0), so you'll have to monitor your reference counts and objects yourself.