Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 564
Marnix v. R. Avatar asked Jul 15 '10 15:07

Marnix v. R.


2 Answers

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.

like image 97
BoltClock Avatar answered Sep 30 '22 18:09

BoltClock


If you allocate memory you have to release it. So, yes, put a call to [bar release] or self.bar = nil (if you're using synthesized properties and all that) in your dealloc.

See here for an intro to memory management on iOS.

like image 33
rfunduk Avatar answered Sep 30 '22 18:09

rfunduk