开发者

Memory management with delegates?

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 {
  开发者_C百科  [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

[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 :)


This may shed some light to understand why

The reason that you avoid retaining delegates is that you need to avoid a retain cycle:

A creates B A sets itself as B's delegate … A is released by its owner

If B had retained A, A wouldn't be released, as B owns A, thus A's dealloc would never get called, causing both A and B to leak.

You shouldn't worry about A going away because it owns B and thus gets rid of it in dealloc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜