我需要删除所有用户信息并重新创建。我用来创建所有内容的代码在app delegate中:
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSString* dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
NSURL *storeURL = [NSURL fileURLWithPath: [dir stringByAppendingPathComponent:
@"Data.sqlite"]];
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;
}
然后,我删除所有内容:
[context reset];
NSString* dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
NSURL *storeURL = [NSURL fileURLWithPath: [dir stringByAppendingPathComponent:
@"Data.sqlite"]];
NSError *error;
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = [((CustomAppDelegate *)[[UIApplication sharedApplication] delegate]) persistentStoreCoordinator];
NSPersistentStore *store = [[storeCoordinator persistentStores] objectAtIndex:0];
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
[storeCoordinator release];
storeCoordinator = nil;
似乎工作正常,当我尝试保存新数据时,问题是,之后。如果我这样做:
NSManagedObjectContext *afterContext = [appDelegate managedObjectContext];
NSEntityDescription *userEntity = [NSEntityDescription entityForName:@"User"
inManagedObjectContext:afterContext];
NSManagedObject *user = [NSEntityDescription
insertNewObjectForEntityForName:[userEntity name] inManagedObjectContext:afterContext];
[user setValue:@"John" forKey:@"firstName"];
if(![afterContext save:&error])
NSLog(@"oops");
它在afterContext保存中崩溃,它给了我一个EXC_BAD_INSTUCTION异常。当我做 [appDelegate managedObjectContext]它创建了新的persistentStore,所以我不知道可能是什么问题。对前一个对象的引用?堆栈跟踪根本没有提供任何线索。
答案 0 :(得分:2)
当我做[appDelegate managedObjectContext]它创建了 新的persistentStore
这是正确的,但前提是它还不存在。你不能“获取”你不拥有的对象,释放它然后将其设置为nil并期望它能够工作。您将storeCoordinator设置为app delegates coordinator的行只是设置指针值。当您在最后释放该协调器并将其设置为nil时,AppDelegate仍设置为现在解除分配的协调器的地址。这就是你崩溃的原因。您需要想出一种在实际AppDelegate本身中释放和取消值的方法。此外,appDelegate中的托管对象上下文将需要更新以反映更改。