Search code examples
objective-ccocoacore-datansarraycontroller

NSArrayController keeps being empty after removing all objects from CoreData


I am using the following method in order to remove all objects from CoreData:

- (void)removeAllObjects:(id)sender{
    [[self managedObjectContext] lock];
    [[self managedObjectContext] reset];
    NSPersistentStore *store = [[[self persistentStoreCoordinator] persistentStores] lastObject]; 

    if (store)
    {
        NSURL *storeUrl = store.URL;
        NSError *error;

        if ([[self persistentStoreCoordinator] removePersistentStore:store error:&error])
        {
            __persistentStoreCoordinator = nil;
            __managedObjectContext = nil;
            __managedObjectModel = nil;
            NSLog(@"storeUrl %@", storeUrl);


            if (![[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:&error])
            {
                NSLog(@"\nresetDatastore. Error removing file of persistent store: %@",[error localizedDescription]);
            }
            else
            {
                NSLog(@"Recreating");
                //now recreate persistent store
               // [self persistentStoreCoordinator];
                [[self managedObjectContext] unlock];
            }
        }
        else
        {
            NSLog(@"\nresetDatastore. Error removing persistent store: %@", [error localizedDescription]);
        }
    }
    else
    {
        NSLog(@"\nresetDatastore. Could not find the persistent store");
    }
}

Everything seem to work great. After deleting everything, I can add new objects again. But the new objects don't appear in my NSArraycontroller, which is bound to the managedObjectContext. After restarting the app all new objects are in the ArrayController (and appear in my tableView)

I checked if the bindings get lost somehow, but everything is correct.

What am I doing wrong? I must miss something that happens at startup. But what? o_O

(I have ARC enabled)


Solution

  • The NSArrayController is bound to the managedObjectContext. When resetting the DB you set the managedObjectContext to nil and afterwards you'll assign a new managedObjectContext. Long story short: You'll need to bind to the new MOC after reset.