NSPrivateQueueConcurrencyType队列为空

时间:2016-09-02 15:40:20

标签: ios objective-c core-data nsmanagedobjectcontext

我有一个像这样堆叠的NSManagedObjectContext:

 - (NSManagedObjectContext *)managedObjectContext {
        if (_managedObjectContext != nil )
        {
           return _managedObjectContext;
        }

        NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
       if (coordinator != nil)
       {
            NSManagedObjectContext* masterContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
            masterContext.undoManager = nil;
            [masterContext setPersistentStoreCoordinator:coordinator];

            NSManagedObjectContext* mainContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
            mainContext.parentContext = masterContext;
            mainContext.undoManager = nil;

            NSManagedObjectContext* workerContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
            workerContext.parentContext = mainContext;
            workerContext.undoManager = nil;

            _managedObjectContext = workerContext;
        }
        return _managedObjectContext;
    }

我在任何地方使用这个上下文来读/写NSManagedObject类型的对象。

这是保存方法,它本质上是递归的并保存更改

+ (void) saveManagedObjectContext:(NSManagedObjectContext *)managedObjectContext withCompletion:(void (^)(BOOL, NSError *))completion
{
       NSLog(@"\nout current queue: %@",[NSOperationQueue currentQueue]);
       [managedObjectContext performBlock:^{
        NSLog(@"\ninside current queue: %@ current thread: %@",[NSOperationQueue currentQueue],[NSThread currentThread]);
        NSError *error  = nil;

        if (![managedObjectContext save:&error]){
            completion(NO, error);
        } else {
            if ([managedObjectContext parentContext] != nil){
            [self saveManagedObjectContext:[managedObjectContext parentContext] withCompletion:completion];
            } else {
                completion(YES, error);
            }
        }
    }];
} 

但每次调用saveManagedObjectContext:方法时,我的应用UI都会冻结。

此外,NSLog语句提供了异常输出:

out current queue: <NSOperationQueue: 0x15c527680>{name = 'NSOperationQueue Main Queue'}
inside current queue: (null) current thread: <NSThread: 0x15c6a86d0>{number = 4, name = (null)}

为什么current queue为空? 为什么我的应用程序冻结或主线程被阻止?

0 个答案:

没有答案