我正在开发一个大量使用sqlite3的应用程序,我面临着一个巨大的内存泄漏问题。
每次我调用这个方法时,当我将对象添加到数组中时,我就会得到内存泄漏。
- (void) makeSitesSelect:(NSString *)dbPath:(NSString *)theSelect {
allSitesSelect = [[NSMutableArray alloc] init];
sqlite3 *database;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql = [theSelect cStringUsingEncoding:NSASCIIStringEncoding];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSMutableArray *selResult = [[NSMutableArray alloc] init]; // <---- Memory leak
NSInteger selprimaryKey = sqlite3_column_int(selectstmt, 0);
[selResult addObject:[NSString stringWithFormat:@"%i", selprimaryKey]]; //<--- memory leak
const unsigned char *chsiteSite = sqlite3_column_text(selectstmt, 1);
const unsigned char *chsiteCity = sqlite3_column_text(selectstmt, 2);
const unsigned char *chsiteCountry = sqlite3_column_text(selectstmt, 3);
const unsigned char *chsiteGPS = sqlite3_column_text(selectstmt, 4);
if (chsiteSite != NULL) {
[selResult addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]]; //<--- memory leak
}
else {
[selResult addObject:@""];
}
if (chsiteCity != NULL) {
[selResult addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)]]; //<---- memory leak
}
else {
[selResult addObject:@""];
}
if (chsiteCountry != NULL) {
[selResult addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 3)]]; //<---- memory leak
}
else {
[selResult addObject:@""];
}
if (chsiteGPS != NULL) {
[selResult addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 4)]]; //<---- memory leak
}
else {
[selResult addObject:@""];
}
[allSitesSelect addObject:selResult];
[selResult release];
}
sqlite3_finalize(selectstmt);
}
sqlite3_close(database);
}
else
sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory.
}任何帮助都是非常感谢的。
谢谢,麦克斯
发布于 2011-08-05 16:55:04
如果你的allSitesSelect是一个属性,那么你应该始终使用self.allSitesSelect = [NSMutableArray alloc init];并且你有责任在不使用后释放。而且你也没有发布数据库。
不需要在while循环中每次都创建selResult
NSMutuableArray selResult*
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
if(selResult == nil){
selResult = [NSMutuableArray copy] //Its an autorelease(you don't need
//release explicitly )
}
}发布于 2011-08-05 16:55:37
你试着这样做
if (!allSitesSelect)
{
allSitesSelect = [[NSMutableArray alloc] init];
}并释放此阵列以取消分配
[allSitesSelect release];https://stackoverflow.com/questions/6953710
复制相似问题