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

时间:2013-07-20 10:18:13

标签: 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;
}

1 个答案:

答案 0 :(得分:21)

错误消息表明<{p>}中searchStringnil

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

如果没有给出搜索字符串,则意图是显示所有对象,您应该这样做 在这种情况下,不要为获取请求分配谓词:

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