How to free "delegate" memories in objective-c?

For my project, I am creating a delegate class. When I assign obj.delegate = self, [self retainCount] is incremented by one. Thus, the assigned object with a save counter is 2. How should the delegate object be freed, and the assigned object is 1?

Relations Srini

+6
objective-c delegates
source share
3 answers

This is a common convention that delegates are not saved. This is mainly due to the fact that the usual template is that the owner of the object is often also its delegate, and if the delegate was saved, you will get a save cycle.

If you use a property, declare it as follows:

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

And remove the line in -dealloc , which frees the delegate.

If accessors are synthesized, you do it. If this is not the case, make accessories the destination of accessories, for example.

 -(DelegateType) delegate { return delegate; } -(void) setDelegate: (DelegateType) newValue { delegate = newValue; } 
+8
source share

In general, you should not hold delegates. The usual template is just their purpose. Otherwise, as you noticed, you will get all kinds of problems with release cycles, etc.

+3
source share

How do you define an accessor for a delegate

 @property (nonatomic, retain) Whatever *delegate; 

or

 @property (nonatomic, assign) Whatever *delegate; 

if it is the first, then the save account will be increased, which is not what you want to do with the delegate. It is the responsibility of the creator to retain the delegate. They only tell you about this and should not preserve it. Its only ability for Obj C to send messages to zero without crashing means that you also shouldn't check the link before use.

+1
source share

All Articles