2012-10-31 66 views
1

如果我在主線程創建的NSFetchRequest像這樣:NSFetchRequest是否包含NSManagedObjectID安全地跨越線程邊界的NSPredicate?

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

它是安全的通過這個NSFetchRequest與包含NSManagedObjectID到後臺線程像這樣的NSPredicate

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

NSPersistentStoreCoordinator *persistentStoreCoordinator = ...; 
[[NSBlockOperation blockOperationWithBlock:^{ 
    NSManagedObjectContext *managedObjectContext = [NSManagedObjectContext new]; 
    [managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator]; 
    NSArray *foos = [managedObjectContext executeFetchRequest:fetchRequest 
                 error:NULL]; 
}] start]; 

回答

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);