【问题标题】:How do I remove a single object in a cell of a UICollectionView?如何删除 UICollectionView 单元格中的单个对象?
【发布时间】:2013-10-16 21:09:08
【问题描述】:

我正在使用 UICollectionView,通过这种方法我可以删除我添加到 CoreData 的所有对象:

- (IBAction)btnDelete:(id)sender {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Are you sure?" message:@"Delete all favorites?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 0){
        nil;
    } else if (buttonIndex == 1){
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = [delegate managedObjectContext];
        NSFetchRequest *execQuery =[[NSFetchRequest alloc] init];
        NSEntityDescription *descOggetto = [NSEntityDescription entityForName:@"HexCode" inManagedObjectContext:context];
        [execQuery setEntity:descOggetto];
        NSError *error = nil;
        _arr = [context executeFetchRequest:execQuery error:&error];

        for (NSManagedObject *ogg in _arr){
            [context deleteObject:ogg];
            [_favoriteCollectionView reloadData];
        }

        NSError *saveError = nil;
        [context save:&saveError];

        // NSLog(@"Delete");
    }
}

如何删除单个对象而不是全部?

【问题讨论】:

  • 视情况而定。您要删除哪个对象?
  • 如果你使用这个命令:[context DeleteObject: ogg] 删除CoreData中的所有对象,而我只想删除单元格中包含的对象。
  • 没有。在您发布的代码中,您正在获取所有对象,遍历它们,并一次删除它们。命令[context deleteObject:ogg]只删除一个对象。

标签: ios objective-c core-data uicollectionview uicollectionviewcell


【解决方案1】:

你没有显示足够的代码让我给你一个具体的答案。但大体是这样的:

首先,您需要获取与要删除的托管对象关联的单元格的索引路径。你如何做到这一点取决于你的用例:

NSIndexPath *indexPath = ...;

从那里,从您的数据模型中获取托管对象。如果您的数据模型是一个可变数组(通常当您的集合视图中只有一个部分时):

NSManagedObject *obj = [self.myDataModel objectAtIndex:indexPath.item];

然后你删除对象并将其从数组中移除:

[obj.managedObjectContext deleteObject:obj];
NSError *saveError = nil
[obj.managedObjectContext save:saveError];
...// error handling
[self.myDataModel removeObject:obj];

最后,您通知集合视图您已经删除了一个项目,以便它可以更新显示:

[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];

或者如果你不想要动画:

[self.collectionView reloadData];

如果您使用的是NSFetchedResultsController,答案会有所不同。如the documentation 中所述,上述一些步骤将在您的NSFetchedResultsControllerDelegate 实施中得到处理。其余步骤如下所示:

NSIndexPath *indexPath = ...;
NSManagedObject *obj = [self.fetchedResultsController objectAtIndexPath:indexPath];
[obj.managedObjectContext deleteObject:obj];
NSError *saveError = nil
[obj.managedObjectContext save:saveError];
...// error handling    

【讨论】:

  • 你写的:self.myDataModel是什么意思?
  • 这是一个引用您的数据模型的假设属性。该行的重点是说明您需要从数据模型中检索给定索引路径的对象。
  • 好的,谢谢。我按照你的建议解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多