I need to delete all user info and recreate it. The code i use to create everything is in the 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");
it crashes in afterContext save, it gaves me a EXC_BAD_INSTUCTION exception. When i do [appDelegate managedObjectContext] it creates the new persistentStore, so i don t know what could be the problem. A reference to a previous object? The stacktrace does not give any clue at all.