Can I just release the top object (iPhone)?
If I release the object that's holding a reference to the variable that I need to release
, is that sufficient? Or must I release
at every level of the containment hierarchy? I fear that my logic comes from working with a garbage collector for too long.
For instance, I assigned to this property of a开发者_JS百科 UIPickerView
instance by hand instead of using IB
@property(nonatomic, assign) id<UIPickerViewDelegate> delegate
Since it's an assign
property, I can't just release
the reference after I assign it. When I finally release
my UIPickerView
instance, do I need to do this:
[singlePicker.delegate release];
[singlePicker release];
or is the second line sufficient?
Also: Are these assign
properties the norm, or is that mostly for Interface Builder? I thought that retain
properties were the normal thing to expect.
The properties are declared assign
instead of retain
for a reason - delegates are not owned by their holders and they don't call release
on them. Otherwise there would be a problem with circular references. You however have to call release on the object you use as the delegate somewhere if you own them.
If delegates were retained, imagine the following situation:
a
takesb
as a delegate, retainsb
b
takesa
as a delegate, retainsa
Now you have a circular reference - without ugly cleanup code that explicitly tells them to release their delegates, both of the objects will never be deallocated.
The subject is treated in Delegation and the Cocoa Application Frameworks:
Delegating objects do not (and should not) retain their delegates. However, clients of delegating objects (applications, usually) are responsible for ensuring that their delegates are around to receive delegation messages. To do this, they may have to retain the delegate in memory-managed code. This precaution applies equally to data sources, notification observers, and targets of action messages. Note that in a garbage-collection environment, the reference to the delegate is strong because the retain-cycle problem does not apply.
精彩评论