views:

61

answers:

2

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

+1  A: 

Hi.

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

[someDelegate release];

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

[self setSomeDelegate:nil];

will not leak.


However, you seem to have [[someDelegate alloc] init] in your viewDidLoad method. 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] to someDelegate=nil;)

Your line in viewDidUnload that 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 to viewDidLoad again, your delegate is already nil :)

deanWombourne
Yer I get it, thanks Dean. I was getting confused about how the @property(assign) worked.
fuzzygoat
So given that I have an [[someDelegate alloc] init] in viewDidLoad what happens to that if the view unloads and calls viewDidLoad again? Each time I call viewDidLoad I am going to get a new someDelegate and leak the old one?
fuzzygoat
See the edit I just made :)
deanWombourne
Thanks Dean, I think I can see whats happening, I think I got the wrong idea and now I am fighting to get it to work. I will mark your answer as accepted and go away and rethink this. Much appreciated ...
fuzzygoat
No problem, any more questions just ask :)
deanWombourne
+1  A: 

This may shed some light to understand why

Anders K.
Thank you Anders, thats very helpful also ...
fuzzygoat