views:

33

answers:

1

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 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.

+2  A: 

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 takes b as a delegate, retains b
  • b takes a as a delegate, retains a

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.

Georg Fritzsche
Thanks for that. Would you mind mentioning briefly why it would be a problem with circular references?
Yar
@yar: Added, does that clear it up?
Georg Fritzsche
yes, completely. I never knew why automatic garbage collection was such a big deal. I think I get it now :)
Yar