views:

28

answers:

2

I have below code which is causing memory leak

-(NSString *) getSingRecord: (NSString *) getStatement{

NSString *sql=getStatement;

sqlite3_stmt *statement;

NSString *fieldFlagI=@"0";

if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
    while (sqlite3_step(statement) == SQLITE_ROW) {
        char *fieldFlag=(char *) sqlite3_column_text(statement, 0);
        fieldFlagI=[[NSString alloc] initWithUTF8String:fieldFlag];
        //fieldFlagI=[NSString initWithUTF8String:fieldFlag];
    }
    sqlite3_finalize(statement);
}
//NSString *ffI=fieldFlagI;
//[fieldFlagI release]
return [fieldFlagI];
}

After checking apple documentation i changed code to return [fieldFlagI autorelease];

and in the code segment where i am calling this function

NSString *getRecord=[dbase getSingRecord:flag];

if i do a [getRecord release]; - application crashes - how do i release this object?

A: 

If you do [fieldFlagI autorelease];then variable 'getRecord' don't own the object so you can not release.

once you add object to autorelease pool you can not release the object till you own the object by adding a retain count.

NSString *getRecord=[dbase getSingRecord:flag]; //object is in autorelease pool which will be released by pool
[getRecord retain] //own the object
//do some operation
[getRecord release] //then release
Girish Kolari
A: 

Autorelease the fieldFlagI variable in the method, retain the getRecord result to take ownership of it so that you can release it later. Read through the Memory Management Guide for iOS.

Alex Reynolds