1

我在删除条目时遇到了一些困难Core Data

它可以工作,但 NSManagedObject 数据没有值(错误),因此有时会删除错误的条目。

在我的deleteWholeDatabase方法中,对象填充了值。并且在deleteEntryFromDatabase方法中没有值。但为什么?

这是我的方法:

-(NSArray*)databaseRequest{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:currentEntity inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    NSError *error;
    NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    return items;
}

-(void)deleteWholeDatabase{
    for (NSManagedObject *objectToDelete in [self databaseRequest]) {
        [managedObjectContext deleteObject:objectToDelete];
        NSLog(@"%@ object deleted",objectToDelete);
    }
    [self saveContext];
    NSLog(@"All entries deleted!");
}

-(void)deleteEntryFromDatabase:(NSManagedObjectContext*)context forEntry:(NSIndexPath*)indexPath{
    NSManagedObject *objectToDelete=[[self databaseRequest] objectAtIndex:indexPath.row];
    [managedObjectContext deleteObject:[managedObjectContext objectWithID:[objectToDelete objectID]]];
    [self saveContext];
    NSLog(@"%@ deleted!",[managedObjectContext objectWithID:[objectToDelete objectID]]);
}
4

2 回答 2

0

我不会在任何地方保留调用[self databaseRequest],而是将本地副本保留NSManagedObjectID's为数组。

- (void)init {
    self.entities = [self databaseRequest];
}

-(NSArray*)databaseRequest{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:currentEntity inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    NSError *error;
    NSArray *items = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

    NSMutableArray *itemIDs = [[NSMutableArray alloc] initWithCapacity:[items count]];
    for (NSManangedObject *item in items) {
        [itemIDs addObject:[item objectID]];
    }

    return items;
}

那么无论你在哪里打电话[self databaseRequest],你都会得到正确的NSManagedObjectID。然后你只需要从 ID 中获取正确的实体。

于 2013-02-15T15:40:17.763 回答
0

错误的条目被删除,因为每个请求都以不同的顺序返回项目。尝试通过比较它们的内存地址来删除它们

于 2013-02-15T14:57:27.473 回答