我想備份一個核心數據SQLite數據庫。此代碼成功處理正在運行的數據庫併合並WAL文件。不幸的是,每次運行時,我都會在內存佔用空間中看到大約3-5 MB的凹凸。程序運行一段時間後,這會導致問題。有人可以幫我回收內存嗎?我認爲將所有東西都設置爲零將從RAM中釋放所有的對象,但似乎並不是這樣。在iOS中的核心數據內存足跡不斷增加
-(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" }};
}
註釋掉migrationSuccess點之後出現這種情況不會影響內存佔用的一切。
哇,我不知道你是怎麼想出來的,但是這似乎也解決了我的問題。內存佔用量將無限增長(超過1GB),現在可以輕鬆生活在25MB。 –