Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSInvalidArgumentException', reason: 'Invalid predicate: nil RHS, need help figuring this out

I've read other posts about this crash having something to do with the predicate returning nil but im unable to figure this out with my app. Can someone please help me with this?

static NSString *const KJMWorkoutCategorySectionKeyPath = @"workoutCategory";

- (NSFetchedResultsController *)fetchedResultsControllerWithSearchString:(NSString *)searchString {
    NSManagedObjectContext *sharedContext; // my NSManagedObjectContext instance...

    NSFetchRequest *request = [NSFetchRequest new];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Workouts"
                                              inManagedObjectContext:sharedContext];
    request.entity = entity;
    request.predicate = [NSPredicate predicateWithFormat:@"(workoutName CONTAINS[cd] %@)", searchString];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:KJMWorkoutCategorySectionKeyPath ascending:YES];
    request.sortDescriptors = @[sortDescriptor];

    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                                               managedObjectContext:sharedContext
                                                                                                 sectionNameKeyPath:KJMWorkoutCategorySectionKeyPath
                                                                                                          cacheName:nil];
    fetchedResultsController.delegate = self;

    NSError *error = nil;

    if (![fetchedResultsController performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }

    return fetchedResultsController;
}
like image 364
kevnm67 Avatar asked Jul 20 '13 10:07

kevnm67


1 Answers

The error message indicates that searchString is nil in

NSPredicate *filterPredicate = [NSPredicate 
            predicateWithFormat:@"(workoutName CONTAINS[cd] %@)", searchString];

If the intention is to display all objects if no search string is given, you should just not assign a predicate to the fetch request in that case:

if ([searchString length] > 0) {
    NSPredicate *filterPredicate = [NSPredicate 
            predicateWithFormat:@"(workoutName CONTAINS[cd] %@)", searchString];
    [request setPredicate:filterPredicate];
}
like image 191
Martin R Avatar answered Sep 17 '22 14:09

Martin R