【发布时间】:2011-07-27 15:46:49
【问题描述】:
我的应用程序中有 3 个内存泄漏,但我不知道如何修复它。我对xcode和objective c有点陌生。这是我的代码:
if(sqlite3_prepare_v2( [[DatabaseController sharedDatabaseController] getDb], sqlQueryConverted, -1, &dbStatement, NULL)==SQLITE_OK){
//Run the query
while ( sqlite3_step(dbStatement) == SQLITE_ROW )
{
const char *name = (const char *)sqlite3_column_text(dbStatement, 0);
int courseId = sqlite3_column_int(dbStatement, 1);
const char *location = (const char *)sqlite3_column_text(dbStatement, 2);
const char *date = (const char *)sqlite3_column_text(dbStatement, 3);
//Convert the returnedElement char to string
nameConverted = [[NSString alloc] initWithUTF8String:name];
locationConverted = [[NSString alloc] initWithUTF8String:location];
dateConverted = [[NSString alloc] initWithUTF8String:date];
Course *course = [[[Course alloc]initWithName:nameConverted _id:courseId location:locationConverted courseDate:dateConverted] autorelease];
//Add the course to the to a temporary list to remove duplicated items
[tempResults addObject:course];
}
[nameConverted release];
[locationConverted release];
[dateConverted release];
}
我也尝试过自动释放它。此代码用于过滤搜索并重新加载搜索显示表。如果我将release 行放在while 语句中,如果我输入2 个字母,应用程序就会崩溃。我该如何解决这个问题?
谢谢。
编辑:我一直在来回解决这个问题,但没有运气。我得出的结论是 Instruments 有问题,因为它仍然显示内存泄漏。这是今天的代码,我认为应该可以解决问题:
NSString *nameConverted = [[NSString alloc] initWithUTF8String:name];
NSString *locationConverted = [[NSString alloc] initWithUTF8String:location];
NSString *dateConverted = [[NSString alloc] initWithUTF8String:date];
Course *course = [[[Course alloc]initWithName:nameConverted _id:courseId location:locationConverted courseDate:dateConverted] autorelease];
//Add the course to the to a temporary list to remove duplicated items
[tempResults addObject:course];
course = nil;
[course release];
[nameConverted release];
nameConverted = nil;
[locationConverted release];
locationConverted = nil;
[dateConverted release];
dateConverted = nil;
NSLog(@"course retain count %i",[course retainCount]);
NSLog(@"name coverted retain count %i",[nameConverted retainCount]);
NSLog(@"location coverted retain count %i",[locationConverted retainCount]);
NSLog(@"date coverted retain count %i",[dateConverted retainCount]);
日志告诉我retainCount = 0;,所以我不明白为什么会有内存泄漏。大家能给我一些建议吗?
再次感谢。
【问题讨论】:
-
课程 = 无; 【课程发布】;是泄漏。通过将其设置为 nil,您将丢失对象而无需释放它。只需使用 [course release] 即可发布。
标签: iphone objective-c cocoa-touch