gpt4 book ai didi

ios - 嵌套的 performBlock : on NSManagedObjectContext

转载 作者:可可西里 更新时间:2023-11-01 03:09:39 30 4
gpt4 key购买 nike

当为 NSManagedObjectContext 使用 NSPrivateQueueConcurrencyTypeNSMainQueueConcurrencyType 类型时,在同一上下文中进行嵌套的 performBlock 调用是否安全?

[backgroundContext performBlock:^{
NSFetchRequest *myRequest = ...;
__block NSArray *result= nil;
[backgroundContext performBlockAndWait:^{
results = [backgroundContext executeFetchRequest:myRequest error:NULL];
}];
}];

这可能看起来很愚蠢,但我有一个现有的代码库,其中包含许多封装 executeFetchRequest 调用的辅助方法。我不想假设调用者是否已经使用过 performBlock。例如:

-(void)updateObjects:(BOOL)synchronous
{
if (YES == synchronous)
[self fetchHelper];
else
{
[backgroundContext performBlock:^{
[self fetchHelper];
}];
}
}

-(NSArray*)fetchHelper
{
[self.backgroundContext performBlockAndWait:^{
//Fetch the objects...
[self.backgroundContext executeFetchRequest: (...)];
}];
}

我试过了,效果不错。但是我学会了(通过艰难的方式)对核心数据和多线程要非常小心。

最佳答案

是的,performBlockAndWait 是可重入的。直接来自 Apple 的发行说明...

Core Data formalizes the concurrency model for the NSManagedObjectContext class with new options. When you create a context, you can specify the concurrency pattern to use with it: thread confinement, a private dispatch queue, or the main dispatch queue. The NSConfinementConcurrencyType option provides the same behavior that was present on versions of iOS prior to 5.0 and is the default. When sending messages to a context created with a queue association, you must use the performBlock: or performBlockAndWait: method if your code is not already executing on that queue (for the main queue type) or within the scope of a performBlock... invocation (for the private queue type). Within the blocks passed to those methods, you can use the methods of NSManagedObjectContext freely. The performBlockAndWait: method supports API reentrancy. The performBlock: method includes an autorelease pool and calls the processPendingChanges method upon completion.

关于ios - 嵌套的 performBlock : on NSManagedObjectContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10445246/

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