基本上,我想做的是清除CoreData持久存储中的所有数据,然后导入新数据。你会怎么做?似乎最简单的解决方案是调用
非常感谢,
#
问题0.1:是什么
我正在尝试更新CoreData持久存储中的数据。我的用户看到一个包含统计数据的表格视图。我想通过删除所有现有数据,然后导入新数据来更新应用程序。我希望显示进度视图,告诉用户应用程序没有挂起。
我已经在我的AppDelegate中添加了以下resetPersistentStore方法(persistentStoreCoordinator供参考):
[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_ACCESS
的错误...
我不太了解CoreData或多线程,可能会犯一些明显的错误...