Hi am new to using Parse and am trying to load a simple Table View Controller with data from an array retrieved using Parse PFQuery. Though I can nslog the "categories" array in view did load, by the time the code reaches numberOfRowsInSection the array seems to have been reset to nil. Any help with this would be greatly appreciated. Btw I did try this loading the code into an array with literals and no problem the table was displayed fine. Heres the code:
@implementation DisplayCategoriesTVC
NSArray *categories;
- (void)viewDidLoad {
[super viewDidLoad];
// CODE TO RETRIEVE CONTENTS OF THE PARSE CATEGORIES CLASS
PFQuery *query = [PFQuery queryWithClassName:@"Categories"];
// [query whereKey:@"Sequence" > @1];
[query findObjectsInBackgroundWithBlock:^(NSArray *categories, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(@"Successfully retrieved %lu categories.", (unsigned long)categories.count);
} else {
// Log details of the failure
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [categories count];
}
The specfic question I have is, why at the numberOfRowsInSection is the categories array showing nil value?
The specific question I have is why does the categories array now show nil and what can I do to keep the values that were loaded by the PFQuery and use them in my other methods?
You're performing something on the background thread:
findObjectsInBackground:
What does this mean since you're new?
So how do you reload the tableView when your data finally does aggregate from the background task?
You simply, reload the tableView, but we need to do it on the main thread because UI updates happen there:
[self.tableView reloadData];
For more info see :
iPhone - Grand Central Dispatch main thread
So completely:
PFQuery *query = [PFQuery queryWithClassName:@"Categories"];
// [query whereKey:@"Sequence" > @1];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(@"Successfully retrieved %lu categories.", (unsigned long)categories.count);
self.categories = objects;
//Since this is a UI update we need to perform this on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
} else {
// Log details of the failure
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
Your query has completed its task before your UI is updated because it's happening on the background thread, so you need to tell your UI components when it is done.