我正在为我的 iOS 应用程序使用 Core Data,在我的 fetch 请求中,我通过某个属性执行 fetch GROUP。因为我必须 GROUP BY,所以结果类型是 NSDictionary 而不是托管对象。
表格视图工作正常,我面临的唯一问题是删除该行。它不会删除行,上下文也不会删除对象。
我做了一些挖掘,发现如果我的结果类型是托管对象,那么上下文可以删除对象并且表视图行被删除,但是 GROUP BY 功能丢失了,因为它仅在结果类型是 NSDictionary 对象时才有效.
任何帮助,将不胜感激。
这就是 FETCH REQUEST 方法(已编辑)
NSError * anyError = nil;
AppDelegate * applicationDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = [applicationDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Merchant" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"premiumActName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setSortDescriptors:descriptors];
NSPropertyDescription *accountDesc = [[entity propertiesByName] objectForKey:@"premiumActName"];
NSExpressionDescription* objectIdDesc = [NSExpressionDescription new];
objectIdDesc.name = @"objectID";
objectIdDesc.expression = [NSExpression expressionForEvaluatedObject];
objectIdDesc.expressionResultType = NSObjectIDAttributeType;
NSArray *propertiesToFetch= @[accountDesc, objectIdDesc];
[request setPropertiesToFetch:propertiesToFetch];
[request setPropertiesToGroupBy:[NSArray arrayWithObjects:accountDesc, nil]];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
NSArray *distinctResults = [context executeFetchRequest:request error:&anyError];
NSLog(@"function=%s", __PRETTY_FUNCTION__);
NSLog(@" result =%@", distinctResults);
if(!_fetchedResultsController)
{
_fetchedResultsController = nil;
}
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
if(![_fetchedResultsController performFetch:&anyError])
{
NSLog(@" Error =%@", anyError);
}
if (![context save:&anyError])
{
// Handle the error.
}
那是表视图删除行方法(已编辑)
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *applicationDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = [applicationDelegate managedObjectContext];
NSDictionary * dictionary = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSManagedObjectID * iod = [dictionary objectForKey:@"objectID"];
NSManagedObject * object = [context objectWithID:iod];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[context deleteObject:object];
// Commit the change.
NSError *error = nil;
if (![context save:&error])
{
NSLog(@"Couldn't save: %@", error);
}
}
[self.membersTblView reloadData];
}
这也不会删除对象和表格视图行!