Memory management with delegates, it is my understanding that I don’t retain delegates, I am a little unsure about what to do with the delegate if the view gets unloaded (via viewDidUnload) and later recreated (via viewDidLoad)?
@property(assign) SomeClass *someDelegate;
.
- (void)viewDidLoad {
[super viewDidLoad];
someDelegate = [[SomeClass alloc] init];
[someDelegate setDelegate:self];
}
-(void)viewDidUnload {
[super viewDidUnload];
[self setSomeDelegate:nil];
}
-(void)dealloc {
[super dealloc];
}
PS: I might be on the wrong track, I am just trying to get my head round this …
cheers Gary
If you use assign for your property, you’re not calling retain on the object.
This means that you should definitely NOT call release or autorelease on it!
Your line in your dealloc
will cause a crash at some point down in the future – you should remove it. You don’t need to care about assigned properties in the dealloc method.
Your line
will not leak.
However, you seem to have
[[someDelegate alloc] init]in yourviewDidLoadmethod. This is unusual; it’s normal for the delegate to be an external object, not one made by yourself. In your case, it’s not really a delegate, it’s just an object that does something for you – you should rename it and change the property to a retain (and remember to release it in dealloc).Currently, if your property is set to (assign) and someone else sets it, you will leak your initial delegate. If you only use the delegate inside this class, perhaps it shouldn’t be a property at all? If you just want to be able to read it from outside your class you might be able to use (readonly) instead of assign (and change
[self setSomeDelegate:nil]tosomeDelegate=nil;)Your line in
viewDidUnloadthat sets the delegate to nil removes the issue you raise in your second comment – you’re removing the delegate so by the time you get toviewDidLoadagain, your delegate is already nil 🙂