【发布时间】:2011-01-17 19:40:14
【问题描述】:
基本上,我要做的是清除我的 CoreData 持久存储中的所有数据,然后导入新数据。你会怎么做?似乎最简单的解决方案是调用[NSPersistentStoreCoordinator removePersistentStore:error:],然后删除该文件。这是最好的做法吗?它是线程安全的吗?
非常感谢,
#
问题 0.1:是
我正在尝试更新 CoreData 持久存储中的数据。我的用户正在查看带有统计数据的表格视图。我想通过删除所有现有数据来更新应用程序,然后导入新数据。我想显示一个进度视图来告诉用户应用程序没有挂起。
我在我的 AppDelegate 中添加了以下resetPersistentStore 方法(persistentStoreCoordinator 供参考):
// ...
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
// ...
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: kPersistentStoreFilename]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
/**
* Will remove the persistent store
*/
- (NSPersistentStoreCoordinator *)resetPersistentStore {
NSError *error;
[managedObjectContext lock];
// FIXME: dirty. If there are many stores...
NSPersistentStore *store = [[persistentStoreCoordinator persistentStores] objectAtIndex:0];
if (![persistentStoreCoordinator removePersistentStore:store error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// Delete file
if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// Delete the reference to non-existing store
[persistentStoreCoordinator release];
persistentStoreCoordinator = nil;
NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];
[managedObjectContext unlock];
return r;
}
然后在我看来我这样做(在另一个线程中,因为我使用的是MBProgressHUD:
PatrimoineAppDelegate *appDelegate = (PatrimoineAppDelegate *)[[UIApplication sharedApplication] delegate];
// Delete everything
[appDelegate resetPersistentStore];
我得到一个EXC_BAD_ACESS...
我不太了解CoreData或多线程,也许我正在做一个明显的错误......
【问题讨论】:
-
我也很想知道怎么做。
-
使用预写锁定 (WAL) 是个坏主意。磁盘上也会有 wal 和 shm 文件。
标签: iphone multithreading core-data