我有以下代码,它显示了使用stringWithUTF8String在语句附近对象收藏的内存泄漏。
我已经在物业中宣布了最爱
-(NSMutableArray *) readFavoritesFromDatabase
{
// Check if database is present
[self setDatabaseNameAndPath];
[self checkAndCreateDatabase];
// Setup the database object
sqlite3 *database;
//Initialize favorites array
if (favorites == nil)
{
[favorites release];
favorites = [[NSMutableArray alloc] init];
}
else
{
favorites = nil;
[favorites removeAllObjects];
}
// Open the database from the users file system
if(sqlite3_open([self.dataBasePath UTF8String], &database) == SQLITE_OK)
{
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from Favorites";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the favorites array
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// Create Favorite object and add it to the Favorite array
Favorite *favorite = [[[Favorite alloc] init] autorelease];
favorite.cameraID = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(compiledStatement, 0)];
favorite.cameraName = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(compiledStatement, 1)];
favorite.cameraLink = [NSString stringWithUTF8String:(const char*)sqlite3_column_text(compiledStatement, 2)];
[self.favorites addObject:favorite];
//[favorite.cameraID release];
// [favorite.cameraName release];
// [favorite.cameraLink release];
}
// If favorite cameras exists in database, then sort the Favorites array
if([self.favorites count]>0)
{
NSSortDescriptor *favoritesNameSorter = [[NSSortDescriptor alloc] initWithKey:@"cameraName" ascending:YES];
[self.favorites sortUsingDescriptors:[NSArray arrayWithObject:favoritesNameSorter]];
[favoritesNameSorter release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
// Close the database
if(database !=nil)
{
sqlite3_close(database);
return self.favorites;
}
else
{
return nil;
}
}
请让我知道如何解决此内存泄漏问题 提前谢谢。
答案 0 :(得分:1)
使用这种安全方法:
Favorite *tempFavorite = [[Favorite alloc] init];
self.favorite = tempFavorite;
[tempFavorite release];
Normaly,在您最喜欢的dealloc函数中,您应该在调用super dealloc函数之前删除所有对象并清除必要的内容。
使用这种方式,你不需要担心喜欢是否为零,因为objective-c允许调用nil对象的方法
此致
Meir Assayag
答案 1 :(得分:1)
不确定stringWithUTF8String
泄漏,但这是一个问题:
favorites = nil;
[favorites removeAllObjects];
你泄漏favorites
中的内容然后告诉nil
对象删除所有对象 - 它是零,根据定义它没有。然后你尝试添加对象;这也行不通。
答案 2 :(得分:-1)
我没有看到你的stringWithUTF8String有任何泄漏,该代码效果很好。但是,看看整个方法,我发现有些东西会产生内存问题,如泄漏或崩溃。如果您已经为收藏夹声明了一个属性,那么您应该在这里使用self.favorites
//Initialize favorites array
if (favorites == nil)
{
[favorites release];
favorites = [[NSMutableArray alloc] init];
}
else
{
favorites = nil;
[favorites removeAllObjects];
}
变为:
//Initialize favorites array
if (self.favorites == nil)
{
self.favorites = [[NSMutableArray alloc] init];
}
else
{
self.favorites = nil;
}
它会帮助你处理内存管理中的很多事情,比如在你的其他情况下,你将变量设置为nil但不释放它,在第一个条件下,你释放一个nil对象?