gpt4 book ai didi

iPhone 由于 stringWithUTF8String 导致内存泄漏

转载 作者:行者123 更新时间:2023-12-03 21:22:11 24 4
gpt4 key购买 nike

我有以下代码,显示了 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;
}
}

请告诉我如何解决这个内存泄漏问题提前致谢。

最佳答案

使用这种安全的方法:

Favorite *tempFavorite = [[Favorite alloc] init];
self.favorite = tempFavorite;
[tempFavorite release];

通常,在您最喜欢的 dealloc 函数中,您应该在调用 super dealloc 函数之前删除所有对象并清理必要的对象。

使用这种方式,你不需要担心 favorite 是否为 nil,因为 Objective-C 允许调用 nil 对象的方法

问候

梅厄·阿萨亚格

关于iPhone 由于 stringWithUTF8String 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3649472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com