【问题标题】:NSManagedObjectContext: autoupdate or not?NSManagedObjectContext:自动更新与否?
【发布时间】:2010-07-23 14:45:55
【问题描述】:

我需要了解一些有关 NSManagedObjectContext 更新的信息。 我有一个 UISplitView,在 RootView 上有一个 UITableViewController,在 Detail View 上有一个 UIViewController。当我连续点击数据时,我会将一些数据加载到标签和 UITextView 中,我可以在其中更新该字段:

- (void)textViewDidEndEditing:(UITextView *)textView {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
[[listOfAdventures objectAtIndex:indexPath.row] setAdventureDescription:textView.text];
}

好的。这工作正常,描述已更新。 另外,有人可能想删除一行:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"playerPlaysAdventure.adventureName==%@",[[listOfAdventures objectAtIndex:indexPath.row] adventureName]];
    NSArray *results = [[AdventureFetcher sharedInstance] fetchManagedObjectsForEntity:@"Player" withPredicate:predicate withDescriptor:@"playerName"];

    [moc deleteObject:[listOfAdventures objectAtIndex:indexPath.row]];
    for ( Player *player in results ) {
        [moc deleteObject:player];
    }
    [listOfAdventures removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    [self clearDetailViewContent];
    NSError *error = nil;
    if ( ![moc save:&error] ) {
        NSLog( @"Errore nella cancellazione del contesto!" );
        abort();
    }
}   
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}   
}

所以这是我的问题:如果我评论有关保存我的 MOC 的行,冒险只是暂时删除。如果您退出应用程序并重新打开它,该对象仍然存在。更新字段时不会发生这种情况。我想知道为什么以及是否应该将 moc 也保存在 textViewDidFinishEditing 方法中。 先感谢您。

【问题讨论】:

    标签: objective-c ipad core-data nsmanagedobjectcontext


    【解决方案1】:

    这是更改对象的属性与在对象图中添加或删除整个对象之间的区别。

    在第一个块中,您更改现有对象的属性,除非您运行撤消,否则该属性会自动保存。这是因为该对象已经存在于对象图中,并且无需更改其他对象即可进行更改。

    在第二个块中,您将删除整个对象,并可能通过更改对象之间的关系来更改对象图本身。在隐式保存之前不会提交该更改,因为它可能会触发大量对象的级联更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-21
      • 2015-12-23
      • 2013-05-17
      • 2011-12-07
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      相关资源
      最近更新 更多