Why I Cannot release NSString object!

Discussion in 'Mac Programming' started by corycory, Jun 16, 2008.

  1. corycory macrumors newbie

    Jun 16, 2008
    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:mad:"start!"];
    outstr = [outstr stringByAppendingFormat:mad:"%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!
  2. Mac Player macrumors regular

    Jan 19, 2006
    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;
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.


Share This Page