CoreData:替换.sqlite会导致崩溃

时间:2012-03-05 19:20:02

标签: ios core-data automatic-ref-counting nsmanagedobjectcontext

当我更新我的应用程序时,我在启动时使用CoreData模型做了一些事情,之后我将持久存储使用的.sqlite文件替换为:

NSArray *stores = [__persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [__persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}
__persistentStoreCoordinator = nil;
[self persistentStoreCoordinator];

__managedObjectContext = nil;
[self managedObjectContext];

一切都很好,就像它的方式一样。但是当我通过homebutton关闭应用程序时,它会崩溃:

[NSPersistentStoreCoordinator retain]: message sent to deallocated instance

我正在使用ARC ...实际上你可以说这没关系,因为它在关闭时会崩溃,所以你不会注意到崩溃。但是,当然,这不是一个选择,必须有一个正确的方法来做到这一点!?

有什么想法吗?为什么会向NSPersistenStoreCoordinator发送保留?它与__persistentStoreCoordinator = nil;有关,但我需要将其取消,否则它不会使用新的.sqlite。

干杯!

1 个答案:

答案 0 :(得分:3)

最后,我发现了一种更好(和更有效)的方式来替换.sqlite& storeCoordinator的商店,无需使用persistentStoreCoordinator:

NSArray *stores = [__persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [__persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}

NSString *storePath = [[self applicationDocumentsDirectoryString] stringByAppendingPathComponent:@"PictureApp.sqlite"];

NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectoryString] stringByAppendingPathComponent:@"PictureApp.sqlite"]];

NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"PictureApp" ofType:@"sqlite"];
if (defaultStorePath) {
    [[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}

NSError *error = nil;
[__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error];
相关问题