简体   繁体   English

删除核心数据中的对象

[英]Delete objects in core data

I'm trying to delete all objects in a core data entity.我正在尝试删除核心数据实体中的所有对象。
I've tried with following code, but keep getting this error:我尝试使用以下代码,但不断收到此错误:

 'An NSManagedObjectContext cannot delete objects in other contexts.'

Here is the code:这是代码:

- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}


- (void) deleteObjects {

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Fixture"];

    NSError *error;
    NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (array == nil) {
        NSLog(@"Error");
    } else {
        NSManagedObject *funFixture = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
        [managedObjectContext deleteObject:funFixture];
    }


}

Your issue is here:你的问题在这里:

NSManagedObject *funFixture = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

You've already executed the fetchRequest, and you have the objects in array .您已经执行了 fetchRequest,并且您拥有array的对象。 You need to delete those objects, not re-run the execute.您需要删除这些对象,而不是重新运行执行。 Something like this:像这样的东西:

for (NSManagedObject* object in array) {
    [managedObjectContext deleteObject:object];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM