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?
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.
[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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With