我正在尝试从我的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
答案 0 :(得分:1)
如果您要删除卡片,则需要在致电[context deleteObject:card model]
之前致电save
- 您正在操纵此关系,但这与实际删除卡片不同。