12

我已经阅读了有关此崩溃的其他帖子,这与返回 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;
}
4

1 回答 1

23

错误信息表明searchStringnil

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

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

if ([searchString length] > 0) {
    NSPredicate *filterPredicate = [NSPredicate 
            predicateWithFormat:@"(workoutName CONTAINS[cd] %@)", searchString];
    [request setPredicate:filterPredicate];
}
于 2013-07-20T13:12:21.683 回答