使用NSFetchedResultsController后,TableView保持为空

时间:2013-08-16 10:08:54

标签: ios core-data tableview nsfetchedresultscontroller

我尝试使用NSFetchedResultsController来显示我的tableView部分。但现在我的tableView保持空白。

 @property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;


- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (void)viewDidLoad
{
   self.fetchedResultsController = nil;
    self.fetchedResultsController.delegate = nil;

}


- (NSFetchedResultsController *)fetchedResultsController {

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];


    // Create and configure a fetch request with the plant entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Travel" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    // Create the sort descriptors array.
    NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    // Create and initialize the fetch results controller.
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"country" cacheName:@"country"];
    self.fetchedResultsController = aFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
    return [sectionInfo numberOfObjects];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @""; }

我遵循了一个教程但是tableView现在是空的。我的tableView工作正常(使用coreData)。 也许有人知道我的问题的答案。感谢。

1 个答案:

答案 0 :(得分:2)

在构建NSFetchedResultsController

后,您似乎忘记了这样做
NSError *error;
BOOL success = [_fetchedResultsController performFetch:&error];