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

[亡魂溺海] 提交于 2019-12-23 10:10:51

问题


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.


回答1:


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.




回答2:


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.




回答3:


Object A is responsible for releasing any references to other objects (Object B, Object C, etc) when it is deallocated-- this doesn't happen automatically.

This is done in the -dealloc method on the object:

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

(or if the properties are read/write and maked as retain, you can substitute [self setPropertyB:nil], etc).

So what will happen is that when all references to Object A go away, it's deallocated, in turn reducing the reference count on properties B and C. If those objects are only owned by Object A, they, too, will end up being deallocated as a result.

(This is true of all iPhone OS development which you've tagged. I assume you're not talking about the garbage-collected environment on the Mac, which has different rules and behavior and does do some things automatically.)




回答4:


The big reason to be using self.bar = nil would be if bar were a reference to a view that was created within a nib file. In that case, one would include that line in -(void)viewDidUnload, as this will let the system release that object when the view is shuffled out. If the view comes back it will be reloaded through the nib file. This does not, however, obviate one from needing to use 'self.bar = nil or [bar release] in -(void) dealloc



来源:https://stackoverflow.com/questions/3256926/objective-c-do-you-have-to-dealloc-property-objects-before-deallocating-the-par

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!