Search code examples
iosnsfetchedresultscontroller

iOS: Simplest way to place results of NSFetch into array


I want to create an array of users. What is the simplest way to get the results of a fetch and place them into an array?

Here is my current code that uses NSFetchedResultsController. Thanks for helping to clear my brain fog...

- (void)viewDidLoad {
    [super viewDidLoad];
NSArray *users = fetchedResultsController;// not working. What should this be?
}

-(NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController==nil){
        NSFetchRequest *fetchRequest= [[NSFetchRequest alloc] init];
        NSManagedObjectContext *context = [chModel sharedInstance].managedObjectContext;
               NSEntityDescription *entity =[NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
        fetchRequest.entity=entity;

        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"date" ascending:NO];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];
        fetchRequest.sortDescriptors=sortDescriptors;

        self.fetchedResultsController=[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
        self.fetchedResultsController.delegate=self;
        NSError *error = nil;
        if (![self.fetchedResultsController performFetch:&error]) {
            NSLog(@"Unresolved error %@,%@",error,[error userInfo]);
            abort();
        }

    }
    _users = [_fetchedResultsController fetchedObjects];
    return _fetchedResultsController;
}

Solution

  • fetchedResultsController is the NSFetchedResultsController instance not any of its contents.

    Since you have to instantiate the results controller to get the fetched objects, move the line

    _users = [_fetchedResultsController fetchedObjects];
    

    into viewDidLoad like

    _users = [self.fetchedResultsController fetchedObjects];