Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to release "delegate" memories in objective-c?

For my project,am creating delegate class. When i assign obj.delegate = self, [self retainCount] get increased by one. So that assigned object having retain count is 2. how should release delegate object and assigned object retaincount is 1?

Regards Srini

like image 543
sri Avatar asked Nov 15 '10 09:11

sri


People also ask

Why delegate is never retained?

The rule is to not retain it because it's already retained elsewhere and more important you'll avoid retain cycles.

Is delegate retained?

The delegate object is retained by the receiver. This is a rare exception to the memory management rules described in Advanced Memory Management Programming Guide. An instance of CAAnimation should not be set as a delegate of itself.


1 Answers

It's the normal convention that delegates are not retained. This is mainly because the usual pattern is that the owner of the object is often also its delegate and if the delegate were retained, you'd get a retain cycle.

If you are using a property, declare it like this:

@property (assign) DelegateType delegate; // replace "DelegateType" with whatever type you need

And remove the line in -dealloc that releases the delegate.

If the accessors are synthesised, you are now done. If not, make the accessors assign accessors e.g.

-(DelegateType) delegate
{
    return delegate;
}

-(void) setDelegate: (DelegateType) newValue
{
    delegate = newValue;
}
like image 187
JeremyP Avatar answered Nov 15 '22 01:11

JeremyP