Core Data管理对象上下文线程同步 [英] Core Data managed object context thread synchronisation

查看:183
本文介绍了Core Data管理对象上下文线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我在一个后台线程更新多对多关系,这在该threa工作正常,但当我发送对象回主线程的更改不显示。如果我关闭应用程序和重新打开数据保存精细,更改显示在主线程。

I'm have an issue where i'm updating a many-to-many relationship in a background thread, which works fine in that threa, but when I send the object back to the main thread the changes do not show. If I close the app and reopen the data is saved fine and the changes show on the main thread. Also using [context lock] instead of a different managed object context works fine.

我已经尝试过NSManagedObjectContext:

I have tried NSManagedObjectContext:

- (BOOL)save:(NSError **)error;
- (void)refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag;    

在整个过程的不同阶段,但似乎并没有帮助。

at different stages throughout the process but it doesn't seem to help.

我的核心数据代码使用以下getter来确保任何操作都是线程安全的:

My core data code uses the following getter to ensure any operations are thread safe:

- (NSManagedObjectContext *) managedObjectContext 
{   

    NSThread * thisThread = [NSThread currentThread];
    if (thisThread == [NSThread mainThread]) 
    {
        //Main thread just return default context
        return managedObjectContext;
    }
    else 
    {
        //Thread safe trickery
        NSManagedObjectContext * threadManagedObjectContext = [[thisThread threadDictionary] objectForKey:CONTEXT_KEY]; 
        if (threadManagedObjectContext == nil)
        {
            threadManagedObjectContext = [[[NSManagedObjectContext alloc] init] autorelease];
            [threadManagedObjectContext setPersistentStoreCoordinator: [self persistentStoreCoordinator]];
            [[thisThread threadDictionary] setObject:threadManagedObjectContext forKey:CONTEXT_KEY];
        }

        return threadManagedObjectContext;
    }
}

-(NSManagedObject*)makeSafe:(NSManagedObject*)object
{
    if ([object managedObjectContext] != [self managedObjectContext])
    {               
        NSError * error = nil;
        object =  [[self managedObjectContext] existingObjectWithID:[object objectID] error:&error];

        if (error) 
        {
            NSLog(@"Error makeSafe: %@", error);
        }
    }

    return object;
}

任何帮助。

推荐答案

如果在后台线程上保存后台上下文,然后在主线程上监听 NSManagedObjectContextObjectsDidChangeNotification $ c> -mergeChangesFromContextDidSaveNotification:在主上下文(在主线程),并且更改将显示在您执行保存后台线程。

If you save the background context on the background thread and then listen for NSManagedObjectContextObjectsDidChangeNotification on the main thread you can call -mergeChangesFromContextDidSaveNotification: on the main context (on the main thread) and the changes will show up as soon as you perform the save on the background thread.

这篇关于Core Data管理对象上下文线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆