NSInvalidArgumentException',原因:'无效的谓词:nil RHS,需要帮助搞清楚这一点

kev*_*m67 10 nspredicate nsfetchedresultscontroller invalidargumentexception

我已经阅读了有关此崩溃的其他帖子与谓词返回nil有关但我无法用我的应用程序解决这个问题.有人可以帮我这个吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 22

该错误消息表示searchStringnil

NSPredicate *filterPredicate = [NSPredicate 
            predicateWithFormat:@"(workoutName CONTAINS[cd] %@)", searchString];
Run Code Online (Sandbox Code Playgroud)

如果打算在没有给出搜索字符串的情况下显示所有对象,那么在这种情况下你不应该为获取请求分配谓词:

if ([searchString length] > 0) {
    NSPredicate *filterPredicate = [NSPredicate 
            predicateWithFormat:@"(workoutName CONTAINS[cd] %@)", searchString];
    [request setPredicate:filterPredicate];
}
Run Code Online (Sandbox Code Playgroud)