When to release a NSString in iPhone

前端 未结 2 875
悲哀的现实
悲哀的现实 2021-02-01 08:40

I have the following method

   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row         


        
相关标签:
2条回答
  • 2021-02-01 09:18

    As epatel said, you don't need to release that particular string. If you wanted to be more proactive, you could do this instead:

    -(NSMutableArray *) getPaises {
        NSMutableArray * paises;
        paises = [[[NSMutableArray alloc] init] autorelease];
        while( get new row ) {
            NSString *aPais =  [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
            [paises addObject:aPais];
            [aPais release];
        }
        return paises;
    }
    

    In summary:

    • [[NSString alloc] initWith...] -> You must release or autorelease.

    • [NSString stringWith...] -> No need to release.

    -- Edit: Added autorelease for paises, as you are returning it. When you return an object, always autorelease it if you have alloc&init'd it.

    0 讨论(0)
  • 2021-02-01 09:25

    stringWithUTF8String: returns an autorelease string which will be released automatically by Cocoa in the next eventloop. But the string is also retained in the array when you do addObject:...so as long as it is in the array it will be retained.

    0 讨论(0)
提交回复
热议问题