views:

677

answers:

2

Hello,

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.

Regards, Pratik

+2  A: 

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.

Ian Henry
Ian, I am not getting what you are saying, can you explain in some detail, please
pratik
A: 

Try:

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

Or:

NSString *_playerName = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];
objPlayer.playerName = _playerName;
[_playerName release];

Please take a moment to read through Apple's memory management guide, which explains this subject.

Alex Reynolds
I tried both the above, but same leak is occurring.
pratik
Maybe you can report where Leaks is saying the leak occurs when using the aforementioned code. That might narrow down the problem somewhat.
Alex Reynolds
Also, `sqlite3_column_text()` returns `const unsigned char *`, and `-initWithUTF8String:` takes a `const char *` according to http://developer.apple.com/mac/library/documentation/cocoa/reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-CJBFGHEH , so there should be no need to cast.
Alex Reynolds
Finally, are you running on the Simulator or on the device, or both? Sometimes the Simulator will report a memory leak that will not occur on the device, and vice versa. That would be useful information, as well.
Alex Reynolds
Basically, the more information you can add to your question, the easier it would be for people to help you.
Alex Reynolds