0

我正在使用 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");
    }
}

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

4

1 回答 1

0

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

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

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. 如文档中所述,上述某些步骤将在您的NSFetchedResultsControllerDelegate实施中得到处理。其余步骤如下所示:

NSIndexPath *indexPath = ...;
NSManagedObject *obj = [self.fetchedResultsController objectAtIndexPath:indexPath];
[obj.managedObjectContext deleteObject:obj];
NSError *saveError = nil
[obj.managedObjectContext save:saveError];
...// error handling    
于 2013-10-17T12:17:24.420 回答