带有NSManagedObjectID的NSPredicate的NSFetchRequest是否可以安全地跨越线程边界?

时间:2012-10-31 19:35:19

标签: objective-c ios multithreading core-data

如果我在主线程上创建了NSFetchRequest,那么:

NSManagedObject *bar = ...;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Foo"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"SELF.bar == %@",
                            [bar objectID]]];

将此NSFetchRequest与包含NSPredicate的{​​{1}}传递给后台线程是否安全?

NSManagedObjectID

1 个答案:

答案 0 :(得分:1)

我在CoreData release notes for iOS 5中找到了一些示例代码,但这看起来还不错。

NSFetchRequest *fr = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
__block NSUInteger rCount = 0;

[context performBlockAndWait:^() {
    NSError *error;
    rCount = [context countForFetchRequest:fr error:&error];
    if (rCount == NSNotFound) {
        // Handle the error.
    }
}];

NSLog(@"Retrieved %d items", (int)rCount);