gpt4 book ai didi

ios - CoreData : removal of 'didSave' notification immediately after save: call. 太快了?

转载 作者:行者123 更新时间:2023-11-29 03:40:46 24 4
gpt4 key购买 nike

-(void)someBackgroundTask {
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
[context setPersistentStoreCoordinator:[self coordinator]];

// ...

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self selector:@selector(handleSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:context];

[context save:&error];

// safe?
[notificationCenter removeObserver:self name:NSManagedObjectContextDidSaveNotification object:context];

// ...
}


// meanwhile on the main thread...
-(void)handleSaveNotification:(NSNotification *)notification {
[[self context] mergeChangesFromContextDidSaveNotification:notification];
}

调用 save: 后这么快就删除观察者是否安全?

最佳答案

只要您收到了想要的通知,就不算太早。但该代码还存在其他问题。

添加观察者、触发通知、然后删除观察者是没有任何意义的。您不妨直接调用 handleSaveNotification 方法,而不必费心处理通知。只需更少的工作就能达到相同的效果。

原因是通知是在发布通知的线程上同步传送的。因此,如果 someBackgroundTask 实际上在后台线程或队列上运行,handleSaveNotification 也将在后台运行。使用这样的通知不会让你跨线程。要在主线程上进行合并,您有几个选项,包括:

  • 使用 addObserverForName:object:queue:usingBlock: 注册通知。使用该方法,您可以告诉通知中心要使用哪个队列。确保保存对此方法返回的对象的引用——稍后您将需要它来删除观察者。
  • 直接调用合并方法,但在该方法中使用 dispatch_asyncperformSelectorOnMainThread:withObject:waitUntilDone: 将合并移至主线程。

关于ios - CoreData : removal of 'didSave' notification immediately after save: call. 太快了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18499733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com