set delegate in objective-c on iOS
- (id)initWithDelegate:(id)delegate
{
self = [super init];
if (self)
{
_delegate = delegate;
}
return self;
}
Is it generally recommended to pass in the delegate in the init method? what about in another method that will be called first?
Also do I need to set _delegat开发者_运维知识库e
to nil
or release in the dealloc
or viewDidUnload
method? and what about the dealloc
or viewDidUnload
method of the controller implementing this delegate?
Is it generally recommended to pass in the delegate in the init method?
That depends on what you want to do. If you will require a delegate every time your object is instantiated, it would be convenient to just pass it in when you init
your object. It's all personal preference, though.
In the code here you are just assigning _delegate
, so there is no need for you to do anything with that particular ivar in your dealloc
or viewDidUnload
methods.
If you have to know a delegate during the init method (or at all), than it is not a delegate. When using the delegation pattern, objects should be able to perform some kind of useful default behavior without their delegate.
Anyways, if you have a parameter your object needs to know no matter what in order to work properly, you should definitely pass it during initialization.
Is it generally recommended to pass in the delegate in the init method? what about in another method that will be called first?
You should only set the delegate at init
when the object might need to communicate with the delegate during initialization, or if the delegate should only be set once during the life of the object. Otherwise it is recommended to set the delegate though a property.
Also do I need to set _delegate to nil or release in the dealloc method? and what about viewDidUnload?
No, _delegate does not need to be set to nil and it only needs to be released if it has been retained.
精彩评论