0

我有一个由核心数据生成的表格视图(table view1)(entity1),我可以一一删除行,但我想用一个按钮一次删除整个表格,我该怎么做?

我有一些东西要删除整个交易,但问题是我有第二个表视图控制器(表 view2),它也是由核心数据生成的(entity2),当我想删除时,"table view1"我也删除了"table view2",我只想删除“table view1”,其内容位于 entity1..

我拥有的删除数据的代码是:

        NSURL *storeURL = [[managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
        // lock the current context
        [managedObjectContext lock];
        [managedObjectContext reset];//to drop pending changes
        //delete the store from the current managedObjectContext
        if ([[managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:nil])
        {
            // remove the file containing the data
            [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
            //recreate the store like in the  appDelegate method
            [[managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:nil];//recreates the persistent store
        }
        [managedObjectContext unlock];
        //that's it !

        [self.tableView reloadData];
4

1 回答 1

9

您必须获取实体的所有对象并删除它们:

NSManagedObjectContext *context = ...; // your managed object context 
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Entity1"];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
    // handle error
} else {
    for (NSManagedObject *object in objects) {
        [context deleteObject:object];
    }
    [context save:&error];
}
于 2013-07-04T22:52:32.577 回答