简体   繁体   中英

Core Data - Datasource methods is called before viewDidLoad

I have noticed that a problem in my app is caused because the Datasource methods of the UITableView are called before viewDidLoad .

The problem is that the UITableView doesn't have the correct amount of rows, it gets the amount of rows from the NSFetchedResultsController but the performFetch "function" for that is called in the viewDidLoad method which for some reason is called after the Datasource methods.

Here's the source of the two important methods:

- (void)viewDidLoad {
    [super viewDidLoad];

 self.tableView.allowsSelectionDuringEditing = NO;
 self.tableView.editing = YES;
 self.title = [NSString stringWithFormat:@"%@", [[game valueForKey:@"title"] description]];

    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

}

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

How do I get past this problem?

The normal program flow calls for the -viewDidLoad to be called before any of the UITableView data source methods. If you are getting them in the reverse order then there is something in your code base causing them to be called out of order.

First, put a breakpoint in both of the methods you have shown in this question and confirm that they are being called out of order.

Then, look at the stack trace when you are in the -tableView:numberOfRowsInSection: breakpoint and see why it is being called before the -viewDidLoad .

Update

The -viewDidLoad is most definitely being called first as shown in the link. When you select the [PlayerViewController -viewDidLoad] line in that stack trace, what line of code is it sitting on? If it is sitting on [super viewDidLoad] then what is your superclass and what is it doing it's -viewDidLoad ?

In my current app, the general code flow would tend to be:

(in the parent controller:)

  • Build the NSFetchRequest based on the relevant parameters of the parent controller.
  • Perform the fetch with NSFetchedResultsController's -performFetch: method
  • If there were no errors, create the results view controller and associate the fetched results controller with it

This approach avoids the issue you're having. It also means that the view that displays results doesn't need to have search logic, and can be reused to show different result sets (though the same result can be achieved by passing in the NSFetchRequest).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM