我改为使用fetchResultController而不是FetchRequest后无法获取数据

时间:2015-10-07 06:36:21

标签: ios objective-c uitableview core-data

我使用下面的代码来获取原始数据:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];

    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
    if (managedObjectContext != nil) {
        NSFetchRequest *fetchRequeset = [[NSFetchRequest alloc] initWithEntityName:@"Restaurant"];

        NSError *e = [[NSError alloc] init];
        restaurants = [managedObjectContext executeFetchRequest:fetchRequeset error:&e];
        if (![managedObjectContext executeFetchRequest:fetchRequeset error:&e]) {
            NSLog(@"%@",e.localizedDescription);
        }
    }
    [self.tableView reloadData];
}

我的tableView可以加载我之前从数据库保存的餐馆对象,我也可以添加新的“餐馆”,它运行良好,但是一旦我用NSFetchedResultsController替换它,它就不能再获取数据了,tableView没有内容:< / p>

- (void)viewDidLoad {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Restaurant"];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    fetchRequest.sortDescriptors = @[sortDescriptor];
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
    if (managedObjectContext != nil) {
        self.fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil];
        self.fetchResultController.delegate = self;

        NSError *e = [[NSError alloc] init];
        restaurants = [self.fetchResultController fetchedObjects];

        if (![self.fetchResultController performFetch:&e]) {
            NSLog(@"%@",e.localizedDescription);
        }
    }
}

为什么?如何解决?

补充说明:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSUInteger rowIndex = [indexPath row];
    Restaurant *restaurant = restaurants[rowIndex];

    cell.nameLabel.text = restaurant.name;
    cell.typeLabel.text = restaurant.type;
    cell.thumbnailImage.image = [UIImage imageWithData:restaurant.image];

    return cell;

}

0 个答案:

没有答案