View displaying on top of loading icon due to asyn

2019-08-14 17:14发布

问题:

I was doing everything in a single thread and have just started moving to asynchronous calls so I'm a bit confused.

What I would like is for the view to load, either with an empty table or with no table at all. The MBProgressHUD should show while the async call gets the data. Then when the data is found the HUD goes away and the table refreshes.

What I have now is everything works except that the HUD is displayed underneath the empty table. Here is the most relevant code.

- (void)awakeFromNib
{
    [super awakeFromNib];
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.dataController = [[StudyController alloc] initWithCredentials:email password:password];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.tableView reloadData];
        });
    });
}

Basically what is happening, I think, is all my code that was rendering the table correctly runs once while the async call is running, and shows an empty table on top of the HUD, and then again after the call when I tell it to reloadData. How do I get it to not run that first time?

Thanks.

回答1:

It's hard to gauge without seeing your table view delegate/datasource methods, but your intuition makes sense. In this case, I can see two options:

  1. Add some logic to your delegate/datasource methods to properly show your loading view if the table is empty.
  2. Rather than add the loading view to the table view, add the loading view to the table view's superview. That way, you can ensure that the loading view is always on top of the table view.

I usually opt for the second method, because I prefer to focus my datasource and delegate methods on only the table view.

Hope this helps!