Delete/Reset all entries in Core Data?

后端 未结 30 3171
天命终不由人
天命终不由人 2020-11-22 16:00

Do you know of any way to delete all of the entries stored in Core Data? My schema should stay the same; I just want to reset it to blank.


Edit

30条回答
  •  长发绾君心
    2020-11-22 16:17

    Here is a somewhat simplified version with less calls to AppDelegate self and the last bit of code that was left out of the top rated answer. Also I was getting an error "Object's persistent store is not reachable from this NSManagedObjectContext's coordinator" so just needed to add that back.

    NSPersistentStoreCoordinator *storeCoordinator = [self persistentStoreCoordinator];
    NSPersistentStore *store = [[storeCoordinator persistentStores] lastObject];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"dataModel"];
    NSError *error;
    
    [storeCoordinator removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
    
    [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
    
    if (storeCoordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:storeCoordinator];
    }
    

提交回复
热议问题