ManagedObjectContext performBlockAndWait用于获取请求?

时间:2016-02-04 21:38:53

标签: ios objective-c core-data objective-c-blocks nsmanagedobjectcontext

如何使用managedObjectContext将我获取的对象传递到performBlockAndWait之外?

-(NSArray *)fetchMyData {

NSManagedObjectContext *context = [self myManagedObjectContext];
context performBlockAndWait:^{
    NSError *error;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    fetchRequest.entity = [NSEntityDescription entityForName:@"data" inManagedObjectContext:context];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    NSArray *fetchedObjects = [context.persistentStoreCoordinator executeRequest:fetchRequest withContext:context error:&error];

    //???? What do I do after fetching my objects?
}



return fetchedObjects;//<---- what do I do to pass my fetchedObject from my block to here?
}

1 个答案:

答案 0 :(得分:1)

你可以这样做:

-(NSArray *)fetchMyData {
    NSManagedObjectContext *context = [self myManagedObjectContext];
    __block NSArray *fetchedObjects;
    [context performBlockAndWait:^{
        NSError *error;
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        fetchRequest.entity = [NSEntityDescription entityForName:@"data" inManagedObjectContext:context];
        [fetchRequest setReturnsObjectsAsFaults:NO];
        fetchedObjects = [context.persistentStoreCoordinator executeRequest:fetchRequest withContext:context error:&error];
    }

    return fetchedObjects;
}