How to clear/reset all CoreData in one-to-many relationship

自作多情 提交于 2019-11-28 00:30:36

I have solved this problem, below is the code,

This function has been written in appdelegate.m

- (void) resetApplicationModel
{
    NSError *error;
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"AppName.sqlite"];
    [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
    for (NSManagedObject *ct in [self.managedObjectContext registeredObjects]) {
        [self.managedObjectContext deleteObject:ct];
    }

    //Make new persistent store for future saves   
    if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // do something with the error
    }  
}

And in my SettingsViewController, I am calling this on resetbutton clicked in this way.

- (void)resetButtonclicked
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate resetApplicationModel];  
}  

Regards Ranjit.

    NSPersistentStore *store = [self.persistentStoreCoordinator.persistentStores lastObject];
    NSError *error;
    NSURL *storeURL = store.URL;
    NSPersistentStoreCoordinator *storeCoordinator = self.persistentStoreCoordinator;
    [storeCoordinator removePersistentStore:store error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
//    Then, just add the persistent store back to ensure it is recreated properly.    
    if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!