[英]Newbie leaks that I don't quite understand
修复了Instruments指示的其他漏洞之后,我发现自己需要帮助,可以通过以下代码找到我的泄漏:
-(void)readHistoryFromDatabase {sqlite3 * database;
NSMutableArray *days = [[NSMutableArray alloc] init];
NSInteger currentMonth;
int noMonths = 0;
int historyCount = 0;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"database.sqlite"];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select data, rata, var, strftime('%m', data) month from rates where id=?";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_int(compiledStatement, 1, id);
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSDate *data = [dateFormat dateFromString:[NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 0)]];
NSString *rata = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 1)];
NSString *var = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 2)];
NSInteger month = sqlite3_column_int(compiledStatement, 3);
if ((currentMonth != month) && (historyCount > 0)) {
[self.rate setValue:[days copy] forKey:[NSString stringWithFormat:@"%d", noMonths]];
noMonths++;
[days removeAllObjects];
currentMonth = month;
} else if (historyCount == 0) {
currentMonth = month;
}
CHis *new = [[CHis alloc] init];
new.rata = rata;
new.var = variatie;
new.month = month;
new.data = data;
historyCount++;
[days addObject:new];
[new release];
}
if ([days count] > 0) {
[self.rate setValue:[days copy] forKey:[NSString stringWithFormat:@"%d", noMonths]];
}
}
sqlite3_finalize(compiledStatement);
}
[dateFormat release];
[days release];
sqlite3_close(database);
}
self.rate是这样定义的:
@属性(非原子的,保留)NSMutableDictionary * rate;
并在viewDidLoad中:
self.rate = [[NSMutableDictionary alloc] init];
基本上,这部分代码从数据库中读取一些速率。 根据月份,它将在NSDictionary中放入两个月和一个包含费率的数组。
我不知道泄漏在哪里。 我知道这也许很简单,但我现在正在寻找2天的解决方案.....
[[NSMutableDictionary alloc] init]
返回保留计数为1的对象。然后将其分配给self.rate
,这会增加保留计数(然后为2)。 如果您为self.rate
分配其他self.rate
,则前一个对象的保留计数将降为1,但不会达到0。
有三种解决方案:
// OK
self.rate = [[[NSMutableDictionary alloc] init] autorelease];
// Better, has the same effect as statement above
self.rate = [NSMutableDictionary dictionary];
// Clumsy, but works
NSMutableDictionary *tmp = [[NSMutableDictionary alloc] init];
self.rate = tmp;
[tmp release];
记住,每次调用alloc/init
或copy
,都会得到一个自己拥有的对象。 这意味着您应立即负责对它们进行release
。 几乎所有其他方法都将/应该返回不需要调用release
的对象,除非您调用retained
以“声明所有权”。
在仪器中,您可以查看泄漏的来源,按扩展的详细信息按钮并选择泄漏,然后您将看到泄漏的来源,方法和文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.