删除</fault>时,iOS NSManagedObject数据<fault>

时间:2013-02-15 14:37:45

标签: ios nsmanagedobject fault

我在删除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]]);
}

2 个答案:

答案 0 :(得分:0)

正在删除错误的条目,因为每个请求都以不同的顺序返回itens。尝试通过比较他们的记忆地址来删除强度

答案 1 :(得分: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中获取正确的实体。