【问题标题】:Refresh UITableView with iCloud changes使用 iCloud 更改刷新 UITableView
【发布时间】:2023-03-29 06:24:01
【问题描述】:

我有一个将核心数据与 iCloud 集成的应用程序。我的视图控制器中有以下通知。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFetchedResults:) name:NSPersistentStoreCoordinatorStoresDidChangeNotification object:coreDataController.psc];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFetchedResults:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coreDataController.psc];

视图控制器包含一个使用NSFetchedResultsController 加载核心数据的UITableView。我不确定在以下方法(由上面的通知调用)中放入什么来刷新表格。我已经尝试重新加载表并重新获取数据但无济于事。我知道 iCloud 正在完成它的工作,因为如果我完全重新加载视图控制器,更改的数据就会显示出来。

- (void)reloadFetchedResults:(NSNotification*)note {
    NSLog(@"Underlying data changed ... refreshing!");

    //_fetchedResultsController=nil;
    //[self fetchedResultsController];

    [theTableView reloadData];


}

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 您真的在刷新数据源吗?还是只是重新加载表格?
  • 好吧,我已经尝试调用 NSFetchResultsController 委托方法来重新获取数据,(注释掉的位)但这也没有用。

标签: ios core-data icloud


【解决方案1】:

您需要获取另一组数据,还是希望查看同一结果集的更改?如果是前者,将其拆除并使用新的谓词、fetch 等重建。然后执行 fetch。

如果是后者,您需要将您的更改与您的 moc 合并。注册通知时,请按如下方式设置:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentContentsImportedChanges:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:self.managedObjectContext.persistentStoreCoordinator];


- (void) documentContentsImportedChanges:(NSNotification*)notification
{
    // Received updates from iCloud
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

【讨论】:

  • 谢谢!是后者。
  • 5 点赞!很棒的答案,和一个很棒的问题。为我工作,谢谢大家!
【解决方案2】:

我同意杰森的回答。但是,您应该确保在正确的线程中执行更新。

[[NSNotificationCenter defaultCenter] addObserver:self
               selector:@selector(persistentStoreDidImportUbiquitousContentChanges:)
                   name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
                 object:_persistentStoreCoordinator];

- (void)persistentStoreDidImportUbiquitousContentChanges:(NSNotification*)note
{
    NSManagedObjectContext *moc = self.managedObjectContext;
    [moc performBlock:^{
        [moc mergeChangesFromContextDidSaveNotification:note];

    }];
}

这种更新 MOC 的方法确保它在与上下文相同的线程中完成,因此您不会发生任何崩溃;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多