View Full Version : Why I Cannot release NSString object!

Jun 16, 2008, 02:55 AM
I wrote a program which is like a daemon, running all time in a while(1) loop, and i have to init a NSString as something like "initwithFormat" in the loop, the following is an example of my code, i cannot create a static string or create outside the loop because i have to mod the string in every loop run in my real case. Now i can't release the str by [string release], and it occupy all my memory in the whole system. what's wrong i did? please help!
long i = 0;
NSString* outstr = [[NSString alloc]initWithFormat:@"start!"];
outstr = [outstr stringByAppendingFormat:@"%d",i];
[outstr release];
it finally ate up all my memory.
but it just can't release the memory, i tried autorelease, NSAutoreleasePool, and garbage collector in xcode 3.0, all just doesn't work!

Mac Player
Jun 16, 2008, 05:45 AM
You are leaking memory because stringByAppendingFormat return a reference to a new String meaning you never release the original string.

You can do something like this:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
int i = 0;
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString* outstr = [[NSString alloc]initWithFormat:@"start!"];
NSString* appended = [outstr stringByAppendingFormat:@"%d",i];
[outstr release];
[pool drain];
return 0;

Jun 16, 2008, 01:39 PM
Mac Player pointed you to the problem, and offered a solution but I thought I'd mention the option of using an NSMutableString rather than an NSString for this example. NSMutableString has a method called appendString: which will allow you to append to it in place. That way you can initWithFormat: then release without having two variables to keep track of.

On a separate subject it might be nice to have a variable done that you check in your while loop, instead of looping forever. You may not need it now, but it will make it easier to change done in a signal handler or under some other condition to nicely exit your program later. No program truly runs forever.