开发者

What is causing memory leaks?

What is causing the leaks in this code? I really cannot understand it. On thes lines: 1: NSMutableArray * days = [[NSMutableArray alloc]init]; 2: [dic setObject:days forKey:key]; 3: [days addObject:value];

The whole method:

-(void) addValueToDictionary: (NSMutableDictionary *) dic withValue: (NSNumber *) value forKey: (NSString *) key {
NSMutableArray * days =  [dic objectForKey:key];
if (days == nil) {
    NSMutableArray * days = [[NSMutableArray alloc]init];
    [days addObject:value];
    [dic setObject:days开发者_StackOverflow forKey:key];
    [days release];
    days = nil;
}
else {
    [days addObject:value];
}

}

BR //Christoffer


Check to make sure that dic is released. You should NSLog retainCount before where you think the final releases are and make sure they are 1 right before the final release.

Also, run a Build and Analyze to make sure you are releasing correctly. The built in Build and Analyze doesn't find as many leaks as running scan-build with all checks, so look into installing scan-build into Xcode as well.

Using an external Xcode Clang Static Analyzer binary, with additional checks


You should be getting a warning about re-declaring days. This may be throwing the leak check off if you are using the static analyser. Modified method below. Mostly coding style changes with a little defensive coding added.

-(void) addValueToDictionary: (NSMutableDictionary *) dic withValue: (NSNumber *) value forKey: (NSString *) key 
{
    if (nil == dic || nil == key || nil == value) return; // bail out on nil parameters 
    if (![dic objectForKey:key]) {
        NSMutableArray * days = [[NSMutableArray alloc] init];
        [dic setObject:days forKey:key];
        [days release];
    }
    [[dic objectForKey:key] addObject:value];
}


Have you tried to change the name of the variable NSMutableArray *days within the if? Don't you get a warning because of that?


There's nothing wrong with that particular piece of code (other than the slightly questionable redefinition of days in the inner scope). Somewhere else you are retaining but forgetting to release the object you put in the dictionary.


change NSMutableArray initialization to...

NSMutableArray * days = [NSMutableArray array];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜