我有一个UIViewController与一个tableView作为子视图。该tableview将有3个部分,我用我的问题PFQueryTableViewController with 3 Sections的答案来完成这一点,但数据没有得到加载到表中。我在viewWillAppear的后台执行我的查询。我担心这是由于嵌套的查询块。我怎样才能解决这个问题?这里是我的代码:嵌套查询块加载数据到UITableView
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
PFQuery *gameQuery = [PFQuery queryWithClassName:@"Game"];
[gameQuery whereKey:@"players" equalTo:[PFUser currentUser]];
[gameQuery orderByDescending:@"createdAt"];
[gameQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error){
self.myTurn = [NSMutableArray array];
self.theirTurn = [NSMutableArray array];
self.gameOver = [NSMutableArray array];
self.allGames = [NSArray array];
for(PFObject *object in objects)
{
if([object objectForKey:@"isOver"] == [NSNumber numberWithBool:YES])
{
[self.gameOver addObject:object];
}
else
{
PFRelation *relation = [object relationForKey:@"whoseTurn"];
PFQuery *relQuery = [relation query];
[relQuery findObjectsInBackgroundWithBlock:^(NSArray *userObjects, NSError *error1){
NSMutableArray *arr = [NSMutableArray array];
for(PFUser *user in userObjects)
{
[arr addObject:user.objectId];
}
if([arr containsObject:[PFUser currentUser].objectId])
{
[self.myTurn addObject:object];
}
else
[self.theirTurn addObject:object];
}];
}
}
self.allGames = [NSArray arrayWithObjects:self.myTurn, self.theirTurn, self.gameOver, nil];
[self.tableView reloadData];
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.allGames count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self.allGames objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
}
PFObject *object = self.allGames[indexPath.section][indexPath.row];
cell.textLabel.text = [object objectForKey:@"numPlayers"];
return cell;
}
您是否设置了一些断点来检查是否有效调用了所有内容,包括子查询中的代码? – Romain 2015-02-12 06:04:12
@Romain当我在这里粘贴代码时,我有一堆日志语句被删除。一切都被调用,看起来好像在我创建“allGames”数组时这些数组是空的。 – Jacob 2015-02-12 06:06:14
您的Parse查询异步运行,因此,在您调用'reloadData'时,'allGames'使用3个空数组进行初始化。由于你的数据结构是已知的(一个由3个数组组成的数组),为什么不用3个空数组*在运行你的Parse查询之前初始化它,然后在回调块中直接更新它(通过适当的线程同步)并最后调用' reloadData'?这最终会更频繁地调用'reloadData',但是iOS应该可以使用它,如果不是,那么稍后您仍然可以使用工作代码在后面找到优化。 – Romain 2015-02-12 06:23:18