How to release several classes which have the same delegate?
(or even just one开发者_如何学运维 class with one delegate)
Say I have a class called DataGetter, which downloads a file from the web. It has a delegate method, which gets triggered when the file has been downloaded:
- (void) dataGetterFinished:(DataGetter *)dataGetter;
So somehere in my code I can set up several files to be downloaded like so:
// in AViewController.m
DataGetter *blueFile = [[DataGetter alloc] init];
blueFile.delegate = self;
[blueFile getData:@"http://example.com/blue-file"];
DataGetter *redFile = [[DataGetter alloc] init];
redFile.delegate = self;
[redFile getData:@"http://example.com/red-file"];
Using clang static analyzer, each alloc line above gets a 'potential leak of an object allocated on line…' error. So how would I release the object. It has to hang around because it has a delegate. So is it OK to release it as the last line of the dataGetterFinished method, like so
- (void) dataGetterFinished:(DataGetter *)dataGetter
{
// code
[dateGetter release];
}
...or should I be using autorelease somehow?
Technically, that works fine, however I would suggest keeping track of the different DataGetters in an NSMutableArray.
For example:
DataGetter *blueFile = [[DataGetter alloc] init];
blueFile.delegate = self;
[blueFile getData:@"http://example.com/blue-file"];
[dataGetters addObject:blueFile]; // dataGetters is an NSMutableArray declared in the .h
[blueFile release];
// Same for red
Then in the delegate method, simple remove the getter from the array:
- (void) dataGetterFinished:(DataGetter *)dataGetter
{
// code
[dataGetters removeObject:dataGetter];
}
The array takes care of retaining the object, and you don't get the analysis warning.
Just be sure to release dataGetters in the dealloc method.
精彩评论