-2

How do I pass my fetched objects outside my performBlockAndWait with my managedObjectContext?

-(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?
}
iamarnold
  • 705
  • 1
  • 8
  • 22
  • It is almost certainly unsafe for you to do this. If the context has thread-affinity (doesn't matter which thread), you don't need the `performBlockAndWait`. If it doesn't, what you are doing is passing managed objects to something which is going to use them outside the correct context. If this method is being called from a context, that context should be provided as a parameter, and you shouldn't use `performBlockAndWait`. – Avi Feb 06 '16 at 18:33

1 Answers1

1

you can do:

-(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;
}
Eric Qian
  • 2,246
  • 1
  • 18
  • 15