我正在尝试重置使用Core Data的应用程序,为此,我编写了以下代码
- (void) resetApplicationModel
{
// NSError *error;
NSError *error;
// retrieve the store URL
NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"abc.sqlite"];
// lock the current context
[self.managedObjectContext lock];
[self.managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[self.managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[self.managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{
// remove the file containing the data
if([[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error])
{
//recreate the store like in the appDelegate method
if([[self.managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error] == nil)
{
NSLog( @"could not create new persistent store at %@ - %@", [storeURL absoluteString], [error localizedDescription]);
}
}
else
{
NSLog( @"could not remove the store URL at %@ - %@", [storeURL absoluteString], [error localizedDescription]);
}
}
else
{
NSLog( @"could not remove persistent store - %@", [error localizedDescription]);
}
[self.managedObjectContext unlock];
__managedObjectContext = nil;
[self managedObjectContext];
_rootViewController.controller = nil;//Make NSFetchResultsController nil;
}
此代码在ios 6.1模拟器上工作正常并且没有问题,但是当我在运行iOS 6.1.3的iphone 4上检查时,持久性文件未被删除,我收到错误
"无法删除文件中的商店网址://localhost/var/mobile/Applications/147E198E-FAB9-46EA-BE4B-4411AFA013FB/Documents/abc.sqlite - 操作无法执行完成。 (可可错误4。)"
但所有数据都被删除了,现在当我尝试在coreData中添加新数据时,我收到错误说
"由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:'此NSPersistentStoreCoordinator没有持久存储。它无法执行保存操作。'"
请帮帮我们
此致 兰吉特
答案 0 :(得分:1)
在NSManagedObjectContext上创建一个类别,然后实现:
- (BOOL)deleteAllObjectsForEntityName:(NSString *)entity withError:(NSError *__autoreleasing *)error {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entity inManagedObjectContext:self]];
[request setIncludesPropertyValues:NO];
NSArray *allObjects = [self executeFetchRequest:request error:error];
if (![self save:error])
return NO;
for (NSManagedObject *object in allObjects)
[self deleteObject:object];
return YES;
}
然后使用它只需:
- (void)deleteAllObjectsForEntityName:(NSString *) entity {
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if (![managedObjectContext deleteAllObjectsForEntityName:entity withError:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
}
传递您的实体名称,它将全部删除: - )