我试图在UITableViewController中显示一些数组。我有一个带有NIB的自定义单元格。我遇到的问题是我的表行尝试在我的ViewDidLoad
中加载数组之前填充。设置断点显示我的表行正在创建,然后直接在我的数组被赋予值(在我的ViewDidLoad
中设置。
有谁可以告诉我为什么tableView
方法在ViewDidLoad
之前运行?在填充表行之前,我需要做些什么来确保我的数组已加载?
这是我的ViewDidLoad
:
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"go");
PFQuery *getCartQuery = [PFQuery queryWithClassName:@"chwCart"];
[getCartQuery whereKey:@"userId" equalTo:[PFUser currentUser].objectId];
[getCartQuery whereKey:@"status" equalTo:@"open"];
[getCartQuery getFirstObjectInBackgroundWithBlock:^(PFObject *currentCartObject, NSError *error) {
// NSLog([currentCartObject objectId]);
currentCart = [currentCartObject objectForKey:@"cartContents"];
dictFoodId = [currentCart valueForKey:@"foodId"];
dictQty = [currentCart valueForKey:@"qty"];
}];
NSLog(@"Should be loaded");
[self.tableView registerNib:[UINib nibWithNibName:@"foodCell" bundle:nil] forCellReuseIdentifier:@"foodCell"];
}
这是我的tableView cellForRowAtIndexPath:
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"foodCell";
foodCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[foodCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.foodTitle.text = [dictQty objectAtIndex:indexPath.row];
return cell;
}
答案 0 :(得分:3)
我认为这是因为您正在将数组更新为运行到后台的块并调用您的委托,只需将tableView重新加载到块完成中
[getCartQuery getFirstObjectInBackgroundWithBlock:^(PFObject *currentCartObject, NSError *error) {
// NSLog([currentCartObject objectId]);
currentCart = [currentCartObject objectForKey:@"cartContents"];
dictFoodId = [currentCart valueForKey:@"foodId"];
dictQty = [currentCart valueForKey:@"qty"];
[self.tableView reloadData];
}];
答案 1 :(得分:3)
您正在使用在后台执行该过程的块,因此创建了tableview并首先调用了委托方法,只需将此行代码添加到viewdidload代码中,该代码将在加载数组后再次调用tableview
**[self.tableView reloadData];**
所以viewdidLoad中的代码应该如下所示
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"go");
PFQuery *getCartQuery = [PFQuery queryWithClassName:@"chwCart"];
[getCartQuery whereKey:@"userId" equalTo:[PFUser currentUser].objectId];
[getCartQuery whereKey:@"status" equalTo:@"open"];
[getCartQuery getFirstObjectInBackgroundWithBlock:^(PFObject *currentCartObject, NSError *error) {
// NSLog([currentCartObject objectId]);
currentCart = [currentCartObject objectForKey:@"cartContents"];
dictFoodId = [currentCart valueForKey:@"foodId"];
dictQty = [currentCart valueForKey:@"qty"];
[self.tableView reloadData];
}];
NSLog(@"Should be loaded");
[self.tableView registerNib:[UINib nibWithNibName:@"foodCell" bundle:nil] forCellReuseIdentifier:@"foodCell"];
}