核心数据保存不持久

Core data save not persisting

我正在尝试从我的 UICollectionView 中删除一个项目。该项目也使用 CoreData 保存。在我重新加载视图或重新启动应用程序之前,删除该项目似乎有效。两者都在下面调用 getCards。当发生这种情况时,我的项目又回来了,甚至在 Core Data 数据库中,该对象似乎还没有被删除。

代码:

    -(void)removeCard:(int)position{
    UserModel *selectedUser = [self getSelectedUserFromDB];

    CardModel *cardToRemove;
    for(CardModel *cardmodel in selectedUser.cards){
        if(cardmodel.position.intValue == position){
            cardToRemove = cardmodel;
            break;
        }
    }
    int positionOldCard = cardToRemove.position.intValue;
    [selectedUser removeCardsObject:cardToRemove];
    NSMutableArray *cards = [selectedUser.cards.array mutableCopy];
    NSLog(@"CARDSCOUNT: %d", cards.count);
    //This changes the position of the cards to accomodate the removing of cards above
    for(CardModel *cardmodel in cards){
        if(cardmodel.position.intValue >  positionOldCard){
            [cardmodel setPosition:[NSNumber numberWithInt:(cardmodel.position.intValue - 1)]];
            [selectedUser replaceObjectInCardsAtIndex:cardmodel.position.intValue withObject:cardmodel];
        }
    }

    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Removing the card failed %@", error);
    }

    NSLog(@"Saved cards: %d", [self getCards].count);
}
    -(NSMutableArray *)getCards{
        UserModel *selectedUser = [self getSelectedUserFromDB];
        NSMutableArray *cards = [[NSMutableArray alloc] init];
        for(CardModel *cardModel in selectedUser.cards){
            [cards addObject:[self modelToCard:cardModel]];
        }
        NSLog(@"Loaded cards: %d", cards.count);
        return cards;
    }

输出:

2015-03-17 11:13:56.259 BeNext[3593:349310] Loaded cards: 4
2015-03-17 11:13:56.260 BeNext[3593:349310] Saved cards: 4
2015-03-17 11:13:56.271 BeNext[3593:349310] Loaded cards: 4
//RELOADING VIEW
2015-03-17 11:14:02.351 BeNext[3593:349310] Loaded cards: 5

如果你想删除卡片,你需要在调用 save 之前调用 [context deleteObject:card model] - 你正在操纵关系,但这与实际删除卡片不同。