views:

41

answers:

2

My app is riddled with memory leaks concerning NSString objects. Never, ever do I use alloc to create an NSString object, yet according to Instruments (used with a real device) the app leaks NSString objects. This happens around uses of stringByAppendingString. Example of code:

NSString *documentsPathPlusSlash = [self.documentsPath stringByAppendingString:@"/"];
NSString *documentsPathPlusSlashAndFileName = [documentsPathPlusSlash stringByAppendingString:fileName];
mainMenuViewController.documentsPath = documentsPathPlusSlashAndFileName;

Once this was one long statement, so I thought maybe splitting it into separate lines would solve it. No such luck, the code above leaks NSString objects. Why is that? MainMenuViewController.dealloc does not release documentsPath, because that's not necessary. Or is it? The Apple documentation and various forums are not really helping.

+2  A: 

Why is that? MainMenuViewController.dealloc does not release documentsPath, because that's not necessary. Or is it?

It depends on how documentsPath property is defined in your mainMenuViewController. If it is defined with retain or copy attribute (which is likely to be so) then your controller "takes ownership" of the string object by incrementing it retain count and it is its responsibility to release it in dealloc method - so you'll need release in this case.

Vladimir
Thanks! Solved. So much for NSString being special objects.
Sander de Jong
So what was the actual problem?
Vladimir
A: 

Depends on how documentsPath is declared and implemented. In the simplest case, when documentsPath is a @property(retain) with @synthesized setter, you still need to set it to nil in your dealloc:

mainMenuViewController.documentsPath = nil
unbeli
Thanks! Solved. Though I prefer [documentsPath release]. Actually, I found a page on the internet showing 5 different ways to implement dealloc. [x release] is what Apple uses in its sample code.
Sander de Jong