在类似的问题中,我无法找到问题的解决方案。我使用fmdb包装器从sqlite数据库中提取了一大堆数据。我的fmdb实用程序类中的方法与此类似:
- (NSMutableArray *) getConnectionsForKey: (NSString *) key
{
NSString *query = [NSString stringWithFormat:@"select * from user" ];
FMResultSet *results = [database executeQuery:query];
NSMutableArray *retArray = [[ NSMutableArray alloc ] init ];
while ([ results next ]) {
NSString *fname = [ results stringForColumn:@"firstname" ];
NSString *lname = [ results stringForColumn:@"lastname" ];
NSMutableDictionary *aDictionary = [[ NSMutableDictionary alloc ]
init
];
[ aDictionary
setObject:fname
forKey:@"firstname"
];
[ aDictionary
setObject:lname
forKey:@"lastname"
];
[ retArray addObject:aDictionary ];
[ aDictionary release ];
}
[ results close ];
return retArray;
}
将我的信息存储在一系列词典中。在我的视图控制器中,我像这样调用我的方法:
-(void) setCurrentConnections: (NSString *) key {
if ( currentConnections != nil ) {
[ currentConnections removeAllObjects ];
}
LocalDatabase *db = [[ LocalDatabase alloc ] init ];
[ db openDatabase ];
currentConnections = [ db getConnectionsForKey:key ];
[ db closeDatabase ];
[ db release ];
}
现在,每次我调用此方法来使用新联系人更新我的数组时,我都会有一致的泄漏,并且在我使用分配工具观察时会不断积累。即使我在从数据库加载后立即释放currentConnections并且从不再次调用此方法,这种情况也会发生,所以我怀疑它是数据库实现的东西。还有其他人处理过这个问题吗?
答案 0 :(得分:1)
currentConnections在'setCurrentConnections'中泄漏。以下是我将如何修复它(注意我也改变了'getConnectionsForKey'来返回一个自动释放的对象)。
- (NSMutableArray *) getConnectionsForKey: (NSString *) key
{
NSString *query = [NSString stringWithFormat:@"select * from user" ];
FMResultSet *results = [database executeQuery:query];
NSMutableArray *retArray = [[ NSMutableArray alloc ] init ];
while ([ results next ]) {
NSString *fname = [ results stringForColumn:@"firstname" ];
NSString *lname = [ results stringForColumn:@"lastname" ];
NSMutableDictionary *aDictionary = [[ NSMutableDictionary alloc ] init];
[ aDictionary
setObject:fname
forKey:@"firstname"
];
[ aDictionary
setObject:lname
forKey:@"lastname"
];
[ retArray addObject:aDictionary ];
[ aDictionary release ];
}
[ results close ];
return [retArray autorelease];
}
-(void) setCurrentConnections: (NSString *) key {
[ currentConnections removeAllObjects ];
[ currentConnections release];
LocalDatabase *db = [[ LocalDatabase alloc ] init ];
[ db openDatabase ];
currentConnections = [ db getConnectionsForKey:key ];
[currentConnections retain];
[ db closeDatabase ];
[ db release ];
}
您可以跳过removeAllObjects
的来电,只需致电发布。原始代码中的问题是您覆盖了对现有currentConnection的引用而没有先释放它,因此导致泄漏。