Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak even though every alloc is released

The last two days I spent with hunting down memory leaks. I´ve read the documentation and searched the internet for good information (e.g. Owen Goss "Finding and Fixing Memory Leaks in iOS Apps"), but still I have too many mysteries to solve.

For example this piece of code lights up in Instruments again and again. I tried my best but can´t fix it.

- (void) updateUserDefaults
{
    // alloc temporary Array for object´s positions
    NSMutableArray *tArray = [[NSMutableArray alloc] init];

    // store locations of objects
    for (int i=0; i<[originalOrigins count]; ++i) {
        CGPoint foo = [self.view viewWithTag:100+i].center;
        NSString *moo = NSStringFromCGPoint(foo);
        [tArray addObject:moo];
        [moo release]; //?
    }

    // retrieve all stored positions for all objects
    NSMutableArray *zettelPannedOrigins = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"zettelPannedOrigins"] mutableCopy] retain];

    // replace with objects from this level
    [zettelPannedOrigins replaceObjectAtIndex:zettelAtIndexInTonebank withObject:tArray];

    // save
    [[NSUserDefaults standardUserDefaults] setObject:zettelPannedOrigins forKey:@"zettelPannedOrigins"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    // clean up memory
    [tArray release];
    [zettelPannedOrigins release]; //?

}

What I think might be interesting for others too is, that I release what I alloc. But still it is leaking. This I can´t answer with the documentation. Or can I?

like image 867
me1974 Avatar asked Dec 31 '25 14:12

me1974


2 Answers

NSMutableArray *zettelPannedOrigins = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"zettelPannedOrigins"] mutableCopy] retain];

This will have a retain count of 2, as mutableCopy retains it once and you are calling retain on it again. Don't call retain here.

Remember, if you call a method with new, alloc, retain or copy in the name, you then own that object and the retain count goes up.

like image 116
Jim Avatar answered Jan 02 '26 06:01

Jim


[NSObject mutableCopy]; will give you back an object with increased retainCount by 1 so you do not need another 'retain'.

NSMutableArray *zettelPannedOrigins = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"zettelPannedOrigins"] mutableCopy] autorelease];

This should do the job :)

like image 40
ludesign Avatar answered Jan 02 '26 05:01

ludesign