Memory leak even though every alloc is released - ios

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

Related

Memory release objective c

Point of my view, when we create object and then set it = nil, this object will be release. but I tried to insert a lot of data to NSMutableDictionary, and then i set NIL for each object. Memory still be there and did not decrease. Please see my code:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableDictionary*frameAnotationLeft=[[NSMutableDictionary alloc] init];;
// Do any additional setup after loading the view, typically from a nib.
NSMutableDictionary * testDict = [[NSMutableDictionary alloc] init];
frameAnotationLeft = [[NSMutableDictionary alloc] init];
for ( int j=0; j<1000; j++) {
for (int i= 0; i<5000; i++) {
NSString* __weak test = #"dule.For the most part, Automatic Reference Counting lets you completely forget about memory management. The idea is to focus on high-level functionality instead of the underlying memory management. The only thing you need to worry about are retain cycles, which was covered in the Properties module.For the most part, Automatic Reference Counting lets you completely forget about memory management. The idea is to focus on high-level functionality instead of the underlying memory management. The only thing you need to worry about are retain cycles, which was covered in the Properties module.For the most part, Automatic Reference Counting lets you completely forget about memory management. The idea is to focus on high-level functionality instead of the underlying memory management. The only thing you need to worry about are retain cycles, which was covered in the Properties module.For the most part, Automatic Reference Counting lets you completely forget about memory management. The idea is to focus on high-level functionality instead of the underlying memory management. The only thing you need to worry about are retain cycles, which was covered in the Properties module.";
NSMutableArray * arrayTest = [[NSMutableArray alloc] init];
[arrayTest addObject:test];
test = nil;
[testDict setObject:arrayTest forKey:[NSString stringWithFormat:#"%d",i]];
arrayTest = nil;
}
[frameAnotationLeft setObject:testDict forKey:[NSString stringWithFormat:#"%d",j]];
}
testDict = nil;
// Begin to release memory
for (NSString* key in frameAnotationLeft) {
NSMutableDictionary *testDict2 = (NSMutableDictionary*)[frameAnotationLeft objectForKey:key];
for (NSString* key2 in testDict2) {
NSMutableArray * arrayTest = (NSMutableArray *)[testDict2 objectForKey:key2];
NSString* test = [arrayTest objectAtIndex:0];
[arrayTest removeAllObjects];
test = nil;
arrayTest = nil;
}
[testDict2 removeAllObjects];
testDict2 = nil;
}
[frameAnotationLeft removeAllObjects];
frameAnotationLeft = nil;
}
Memory when i run it is 218 mb. and it did not decrease. Someone can help me and give me solution? Thank so muuch
If you are using ARC, setting local variables to nil is unnecessary and will have no effect. Local variables are completely memory-managed for you. And setting a variable to nil does not, as you imagine, cause the memory itself to be cleared; it reduces the object's retain count, but that's all. If the object's retain count has fallen to zero, then the memory may be reclaimed at some future time, but you have no control over when that will happen. Thus, your nil setting does nothing whatever, because the same thing is being done for you by ARC anyway.
If you are concerned about accumulation of secondary autoreleased objects during a tight loop (as here), simply wrap the interior of the loop in an #autoreleasepool block.

iOS 8 freezes at updating UserDefaults object

I have a queue of objects stored to the NSUserDefaults. When I need to add objects to it, I call the following method:
+ (void)addCodeToQueue:(Code *)code {
// Note: userDefaults is a static, initialized variable
NSDictionary *codeModel = [self generateCodeModelWith:code];
// Read array from UserDefaults, or create one if nil
NSMutableArray *codeQueue = [userDefaults mutableArrayValueForKey:#"CodeQueue"] ? : [[NSMutableArray alloc] init];
// Add code model
[codeQueue addObject:codeModel];
// Add/replace array & sync
[userDefaults setObject:codeQueue forKey:#"CodeQueue"]; // App freezes here if uncommented
[userDefaults synchronize];
}
My app freezes when I call setObject:forKey. If I add a breakpoint to that line, the continue running, it works. If I don't break, it freezes.
This started happening after I updated Xcode to version 8 and started using the new SDK.
Any hints on this?
I had this problem in several apps as well -- it appears that by returning the mutable array via mutableArrayValueForKey, you can get stuck in a mutex lock. For my code, I swapped this out by:
Getting an immutable array as NSArray *arrSource = [defaults arrayForKey:strKey];
Copying the data into a mutable array:
NSMutableArray *arrMutable = [NSMutableArray arrayWithArray:arrSouce];
Setting my values in arrMutable...
Storing the "modified" array back into the defaults:
[defaults setObject:arrMutable forKey:strKey];
... for me, at least, this has fixed the mutex lock issue.
After my experiment, I have found the minimum code required to generate a mutex lock.
The code is as follows.
NSMutableArray *videoArray = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:VIDEOKEY];
[videoArray addObject:item];
[[NSUserDefaults standardUserDefaults] setObject:videoArray forKey:VIDEOKEY];
There are 3 points to pay attention to:
If I delete [videoArray addObject:item];, the app will crash.
The mutex lock is occurring in [[NSUserDefaults standardUserDefaults] setObject:videoArray forKey:VIDEOKEY];.
If I make a breakpoint at [videoArray addObject:item];, the mutex lock is still exist. If I make it at [[NSUserDefaults standardUserDefaults] setObject:videoArray forKey:VIDEOKEY];, the mutex lock will not exist.
It can be inferred that the mutex lock is result by [NSKeyValueSlowMutableArray addObject:]; and [NSUserDefaults setObject:forKey:]
By the way, my solution to solve it is as follows:
NSMutableArray *mutableVideoArray;
NSArray *videoArray = [[NSUserDefaults standardUserDefaults] arrayForKey:VIDEOKEY];
if (videoArray)
mutableVideoArray = [videoArray mutableCopy];
else
mutableVideoArray = [NSMutableArray array];
if (![mutableVideoArray containsObject:item])
{
[mutableVideoArray addObject:item];
[[NSUserDefaults standardUserDefaults] setObject:mutableVideoArray forKey:VIDEOKEY];
}

reinitialize a NSArray

If I've to reinitialize a NSArray with others values, is it right to do this?
NSArray *array = [[NSArray alloc] initWithObjects:obj1, obj2, nil];
// ...
// some code
// ...
array = [[NSArray alloc] initWithObjects:obj3, obj4, nil];
thanks
Yes this is absolutely right. The new object is completely different than the previous. The object pointer now points to a new object and the old one will be released, since you are using ARC.
It is not exactly the same as reinitializing because you throw away the object and getting a new, but NSArray is immutable so this is the only way to "reinitialize" it.
Your code does not re-initialze an NSArray. It just assigns a new object to the variable array. That's fine.
I thinks this code may help you. At least, I thing this may be a suitable solution, especially if you are using ARC:
NSObject *obj1 = [NSNull null];
NSObject *obj2 = [NSNull null];
NSMutableArray *arrayObj = [NSMutableArray arrayWithObjects:obj1, obj2, nil];
[arrayObj removeAllObjects];
arrayObj = [NSMutableArray arrayWithObjects:obj1, obj2, nil];
I hope it helps you :)
you can reinitialize NSArray with same name ,you will not get any error or warning but the latest objects gets replaced with previous objects.The previous objects overwrites. For this you have to use ARC otherwise memory problem will occurs.

Where are the memory leaks in my for ... in loop with addObject

There seem to be some memory leaks in the following loop:
NSMutableArray *array1 = [[NSMutableArray alloc] init];
for(SomeClass *someObject in array2){ //has already been populated;
if (someObject.field == desiredValue){
[array1 addObject:someObject];
}
}
//EDIT:
//use array1 for very secret operations
[array1 release];
Any ideas why?
Are you releasing all your retained properties in SomeClass of yours? Make sure in dealloc release all retained properties.. Make sure your SomeClass is leak free..

Objective-C: Fixing memory management in a method

I'm almost there understanding simple reference counting / memory management in Objective-C, however I'm having a difficult time with the following code. I'm releasing mutableDict (commented in the code below) and it's causing detrimental behavior in my code. If I let the memory leak, it works as expected, but that's clearly not the answer here. ;-) Would any of you more experienced folks be kind enough to point me in the right direction as how I can re-write any of this method to better handle my memory footprint? Mainly with how I'm managing NSMutableDictionary *mutableDict, as that is the big culprit here. I'd like to understand the problem, and not just copy/paste code -- so some comments/feedback is ideal. Thanks all.
- (NSArray *)createArrayWithDictionaries:(NSString *)xmlDocument
withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *mutableArray = [[[NSMutableArray alloc] init] autorelease];
//NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
CXMLDocument *theXMLDocument = [[[CXMLDocument alloc] initWithXMLString:xmlDocument options:0 error:&theError] retain];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
int i, j, cnt = [nodes count];
for(i=0; i < cnt; i++) {
CXMLElement *xmlElement = [nodes objectAtIndex:i];
if(nil != xmlElement) {
NSArray *attributes = [NSArray array];
attributes = [xmlElement attributes];
int attrCnt = [attributes count];
NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc] init];
for(j = 0; j < attrCnt; j++) {
if([[[attributes objectAtIndex:j] name] isKindOfClass:[NSString class]])
[mutableDict setValue:[[attributes objectAtIndex:j] stringValue] forKey:[[attributes objectAtIndex:j] name]];
else
continue;
}
if(nil != mutableDict) {
[mutableArray addObject:mutableDict];
}
[mutableDict release]; // This is causing bad things to happen.
}
}
return (NSArray *)mutableArray;
}
Here's an equivalent rewrite of your code:
- (NSArray *)attributeDictionaries:(NSString *)xmlDocument withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *dictionaries = [NSMutableArray array];
CXMLDocument *theXMLDocument = [[CXMLDocument alloc] initWithXMLString:xmlDocument options:0 error:&theError];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
for (CXMLElement *xmlElement in nodes) {
NSArray *attributes = [xmlElement attributes];
NSMutableDictionary *attributeDictionary = [NSMutableDictionary dictionary];
for (CXMLNode *attribute in attributes) {
[attributeDictionary setObject:[attribute stringValue] forKey:[attribute name]];
}
[dictionaries addObject:attributeDictionary];
}
[theXMLDocument release];
return attributeDictionaries;
}
Notice I only did reference counting on theXMLDocument. That's because the arrays and dictionaries live beyond the scope of this method. The array and dictionary class methods create autoreleased instances of NSArray and NSMutableDictionary objects. If the caller doesn't explicitly retain them, they'll be automatically released on the next go-round of the application's event loop.
I also removed code that was never going to be executed. The CXMLNode name method says it returns a string, so that test will always be true.
If mutableDict is nil, you have bigger problems. It's better that it throws an exception than silently fail, so I did away with that test, too.
I also used the relatively new for enumeration syntax, which does away with your counter variables.
I renamed some variables and the method to be a little bit more Cocoa-ish. Cocoa is different from most languages in that it's generally considered incorrect to use a verb like "create" unless you specifically want to make the caller responsible for releasing whatever object you return.
You didn't do anything with theError. You should either check it and report the error, or else pass in nil if you're not going to check it. There's no sense in making the app build an error object you're not going to use.
I hope this helps get you pointed in the right direction.
Well, releasing mutableDict really shouldn't be causing any problems because the line above it (adding mutableDict to mutableArray) will retain it automatically. While I'm not sure what exactly is going wrong with your code (you didn't specify what "bad things" means), there's a few general things I would suggest:
Don't autorelease mutableArray right away. Let it be a regular alloc/init statement and autorelease it when you return it ("return [mutableArray autorelease];").
theXMLDocument is leaking, be sure to release that before returning. Also, you do not need to retain it like you are. alloc/init does the job by starting the object retain count at 1, retaining it again just ensures it leaks forever. Get rid of the retain and release it before returning and it won't leak.
Just a tip: be sure that you retain the return value of this method when using it elsewhere - the result has been autoreleased as isn't guaranteed to be around when you need it unless you explicitly retain/release it somewhere.
Otherwise, this code should work. If it still doesn't, one other thing I would try is maybe doing [mutableArray addObject:[mutableDict copy]] to ensure that mutableDict causes you no problems when it is released.
In Memory Management Programming Guide under the topic Returning Objects from Methods (scroll down a bit), there are a few simple examples on how to return objects from a method with the correct memory managment.

Resources