【发布时间】:2015-08-07 08:52:45
【问题描述】:
我正在尝试备份 Core Data SQLite 数据库。此代码成功处理正在运行的数据库并合并 WAL 文件。不幸的是,每次运行时,我都会看到我的内存占用增加了大约 3-5 MB。这会在程序运行一段时间后引起问题。有人可以帮我恢复记忆吗?我认为将所有内容设置为 nil 会释放 RAM 中的所有对象,但似乎并非如此。
-(void) backupDatabaseWithThisTimeStamp: (int) timeStamp withCompletionBlock:(void (^)(void))completion {
NSDate *backupDate = [NSDate date];
NSError *error;
[self.defaultPrivateQueueContext save:&error];
if (error) {
NSLog(@"error -> %@",error);
}
dispatch_async(self.backupQueue, ^{
// Let's use the existing PSC
NSPersistentStoreCoordinator *migrationPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
// Open the store
id sourceStore = [migrationPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[self persistentStoreURL] options:nil error:nil];
if (!sourceStore) {
NSLog(@" failed to add store");
migrationPSC = nil;
} else {
NSLog(@" Successfully added store to migrate");
NSError *error;
NSLog(@" About to migrate the store...");
id migrationSuccess = [migrationPSC migratePersistentStore:sourceStore toURL:[self backupStoreURLwithTimeStamp: timeStamp] options:[self localStoreOptions] withType:NSSQLiteStoreType error:&error];
if (migrationSuccess) {
NSLog(@"store successfully backed up");
// Now reset the backup preference
NSManagedObjectContext *tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
tempContext.persistentStoreCoordinator = migrationPSC;
tempContext.undoManager = nil;
// clip out data
[CDrawColorData purgeDataOlderThan:backupDate fromContext:tempContext];
migrationPSC = nil;
tempContext = nil;
}
else {
NSLog(@"Failed to backup store: %@, %@", error, error.userInfo);
migrationPSC = nil;
}
}
migrationPSC = nil;
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion();
}
});
});
}
self.backupQueue = _backupQueue = dispatch_queue_create("backup.queue", DISPATCH_QUEUE_SERIAL);
localStoreOptions =
- (NSDictionary*)localStoreOptions {
return @{NSMigratePersistentStoresAutomaticallyOption:@YES,
NSInferMappingModelAutomaticallyOption:@YES,
NSSQLitePragmasOption:@{ @"journal_mode" : @"DELETE" }};
}
注释掉迁移成功点之后发生的所有事情不会影响内存占用。
【问题讨论】:
标签: ios core-data memory-leaks