gpt4 book ai didi

iphone - UIManagedDocument 嵌套上下文

转载 作者:行者123 更新时间:2023-12-03 19:41:37 25 4
gpt4 key购买 nike

我一直在阅读苹果文档,但仍然有一个问题,我找不到答案。我有一个 UIManagedDocument 对象,它有两个嵌套上下文 - 主线程上的子上下文和私有(private)线程上的父上下文。接下来,我有一个服务器端。因此,当数据从服务器到达时,我想将其插入后台线程上的托管文档中。

线程安全吗?要创建异步队列,请在其中创建 NSManagedObjectContext 并将其设置为在主线程中创建的父 UIManagedDocument 的子上下文?

dispatch_queue_t fetchQ = dispatch_queue_create("Data fetcher", NULL);
dispatch_async(fetchQ, ^{
//here goes some code for downloading data from the server

NSManagedObjectContext * backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[backgroundContext setParentContext:self.eventDatabase.managedObjectContext]; // is this thread safe?

//some code for creating objects in backgroundContext

NSLog(@"inserting data in background thread");


});
dispatch_release(fetchQ);

换句话说,分配给在主线程上创建的私有(private)线程父级上创建的上下文是否是线程安全的?

最佳答案

您正在使用私有(private)并发类型。这意味着,您应该在其自己的队列上运行代码(通过 PerformBlock)。所以,如果你想这样做,你应该这样做......

NSManagedObjectContext * backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
backgroundContext.parentContext = self.eventDatabase.managedDocument;
backgroundContext.performBlock:^{
//here goes some code for downloading data from the server
//some code for creating objects in backgroundContext

NSLog(@"inserting data in background thread");

// Calling save on the background context will push the changes up to the document.
NSError *error = nil;
[backgroundContext save:&error];

// Now, the changes will have been pushed into the MOC of the document, but
// the auto-save will not have fired. You must make this call to tell the document
// that it can save recent changes.
[self.eventDatabase updateChangeCount:UIDocumentChangeDone];
});

如果您想自己管理队列,您可能应该使用限制 MOC,您应该使用 NSConfinementConcurrencyType 或标准 init 进行初始化,因为这是默认设置。那么,它看起来就像这样......

dispatch_queue_t fetchQ = dispatch_queue_create("Data fetcher", NULL);
dispatch_async(fetchQ, ^{
backgroundContext.parentContext = self.eventDatabase.managedDocument;

//here goes some code for downloading data from the server

NSManagedObjectContext * backgroundContext = [[NSManagedObjectContext alloc] init];

// Everything else is as in the code above for the private MOC.
});
dispatch_release(fetchQ);

关于iphone - UIManagedDocument 嵌套上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10087560/

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