For my project,am creating delegate class. When i assign obj.delegate = self, [self retainCount] get increased 开发者_如何学Goby one. So that assigned object having retain count is 2. how should release delegate object and assigned object retaincount is 1?
Regards Srini
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;
}
In general you shouldn't be retaining delegates. The usual pattern is just to assign them. Otherwise, as you note, you'll get all kinds of problems with release cycles and so forth.
How are you defining the accessor for the delegate
@property (nonatomic, retain) Whatever *delegate;
or
@property (nonatomic, assign) Whatever *delegate;
if it is the former then the retain count will be incremented which is not what you want to be doing with a delegate. It's the responsibility of the creator to keep hold of the delegate. You are only being told about it, and should not retain it. Its only the ability of Obj C to send messages to nil without failing that means you should not be checking the reference before use too.
精彩评论