我有以下代码导致内存泄漏
-(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];
}
检查苹果文档后,我更改了代码以返回[fieldFlagI autorelease];
并在我调用此函数的代码段中
NSString *getRecord=[dbase getSingRecord:flag];
如果我做[getRecord release]; - 应用程序崩溃 - 我如何发布此对象?
答案 0 :(得分:1)
如果您执行[fieldFlagI autorelease];那么变量'getRecord'不拥有该对象,因此您无法释放。
将对象添加到自动释放池后,除非通过添加保留计数来拥有对象,否则无法释放对象。
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
答案 1 :(得分:1)
Autorelease
方法中的fieldFlagI
变量,retain
getRecord
结果取得它的所有权,以便您以后可以发布它。仔细阅读Memory Management Guide for iOS。