gpt4 book ai didi

multithreading - 核心数据和多线程(和绑定(bind)让它更有趣)

转载 作者:行者123 更新时间:2023-12-01 23:25:39 24 4
gpt4 key购买 nike

我有这个后台线程对核心数据对象做一些事情。我得到的上下文如下:

- (id)_managedObjectContextForThread;
{
NSManagedObjectContext * newContext = [[[NSThread currentThread] threadDictionary] valueForKey:@"managedObjectContext"];
if(newContext) return newContext;

newContext = [[NSManagedObjectContext alloc] init];
[newContext setPersistentStoreCoordinator:[[[NSApplication sharedApplication] delegate] persistentStoreCoordinator]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_mergeChangesFromManagedObjectContext:)
name:NSManagedObjectContextDidSaveNotification
object:newContext];

[[[NSThread currentThread] threadDictionary] setValue:newContext forKey:@"managedObjectContext"];
return newContext;
}

然后我获取一些对象,修改它们并保存上下文:

- (void) saveContext:(NSManagedObjectContext*)context {
NSError *error = nil;
if (![context save:&error]) {
[[NSApplication sharedApplication] presentError:error];
}
}

- (void)_mergeChangesFromManagedObjectContext:(NSNotification*)notification;
{
[[[[NSApplication sharedApplication] delegate] managedObjectContext] performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
}

.. 后来我删除了观察者。这适用于主要部分。但是有些属性在合并回来时不会更新。更新之前为零的属性。有值的保持不变。

我试过:

[newContext setMergePolicy:NSOverwriteMergePolicy];

...(和其他合并策略)在主要上下文中,但它不起作用 :P

感谢您的帮助。

注意:我已将值绑定(bind)到 NSTableView。我在合并后记录它们。值为 nil 的值属性似乎工作正常。

最佳答案

您如何为通知注册这两个上下文?你需要做这样的事情:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc addObserver:self
selector:@selector(backgroundContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:backgroundMOC];

[nc addObserver:self
selector:@selector(mainContextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:mainMOC];

并实现回调:

// merge changes in background thread if main context changes
- (void)mainContextDidSave:(NSNotification *)notification
{
SEL selector = @selector(mergeChangesFromContextDidSaveNotification:);
[backgroundMOC performSelector:selector onThread:background_thread withObject:notification waitUntilDone:NO];
}


// merge changes in main thread if background context changes
- (void)backgroundContextDidSave:(NSNotification *)notification
{
if ([NSThread isMainThread]) {
[mainMOC mergeChangesFromContextDidSaveNotification:notification];
}
else {
[self performSelectorOnMainThread:@selector(backgroundContextDidSave:) withObject:notification waitUntilDone:NO];
}
}

关于multithreading - 核心数据和多线程(和绑定(bind)让它更有趣),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307170/

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