我使用通过关系“事件”一对多连接的 2 个实体 Person 和 Event。在我的第一个表格视图中,我有人的名字,第二个我有他们的事件类型。我可以将新事件插入特定的人,但第二个表格视图也没有更新的问题。只有当我使用导航器返回人员并且在它再次发生事件之后我才能看到更改。
对于插入新事件,我使用此方法:
- (void) addEventControllerDidSave:(NSString *)typeData{
NSManagedObjectContext* context = [self managedObjectContext];
Event *newEvent = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:context];
[newEvent setType:typeData];
[currentPerson addEventsObject:newEvent];
NSError *error;
if (![[self managedObjectContext] save:&error])
{
NSLog(@"Problem saving: %@", [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
我如何定义单元格:
//create cell use relation
NSArray *eventsArray = [[[[self currentPerson] events] objectEnumerator]allObjects];
Event *newEvent = [eventsArray objectAtIndex:indexPath.row];
[[cell textLabel]setText: [newEvent type]];
更新表方法:
- (void) controllerWillChangeContent:(NSFetchedResultsController *)controller{
[[self tableView] beginUpdates];
}
- (void) controllerDidChangeContent:(NSFetchedResultsController *)controller{
[[self tableView] endUpdates];
}
- (void) controller: (NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath{
UITableView *tableView = [self tableView];
switch (type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
{
NSArray *eventsArray = [[[[self currentPerson] events] objectEnumerator]allObjects];
Event *newEvent = [eventsArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[[cell textLabel]setText: [newEvent type]];
break;
}
case NSFetchedResultsChangeMove:
{
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
default:
break;
}//switch
}
- (void) controller: (NSFetchedResultsController *) controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch (type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
default:
break;
}
}
我真的不知道如何正确更新 tableView,我更新了我的第一个 tableView 但第二个有我早期描述的问题(可能是因为我使用关系?)你还可以在 git 上看到我的完整项目(也许它有助于):