IPhone + stringWithUTF8String + memory leaks


I am using following code in my application to read the string value from database:

objPlayer.playerName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];

When I run the Instruments to find memory leaks it gives me NSCFString leaks at above line.

What should I do, please help me.


Best Solution

When you set the property playerName, it automatically retains the NSString (even though its constructor autoreleases it). So you'll have to release it again at some point (preferably in the dealloc method).

When you assign a value to a property declared with the retain flag, as in @property(retain), then whenever you assign a value to that property it does three things: releases the old value, assigns the variable to the new value, and retains the new value. Thus the string you're creating through stringWithUtf8String: has a retain count of 1 after that line is executed.

You'll have to release this string at some point, or you'll get a leak. Since it's a property, however, it shouldn't be released before the object that contains it is, so you should put that release statement in your dealloc method.

If none of this really makes sense, take a look at the memory management guide Alex linked to.

Related Question