我有一个静态 UITableView,我想用使用 HTTP 请求(异步运行)检索到的数据来填充它。我试图在几个地方发出 HTTP 请求,但每次来自请求的数据都来得太晚并且没有填充表格视图。我发现填充表格视图的唯一方法是调用reloadData
如下:
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
_accountModel = [[CatapultAccount alloc] init];
[_accountModel getCurrentClient:^ (BOOL completed, NSDictionary *currentAccount) {
if (completed) {
_account = currentAccount;
[self.tableView reloadData];
} else {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:@"Account retrieval unsuccessful"
message:@"Unable to retrieve current account information"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[errorMessage show];
}
}];
}
我试图让请求在主线程上运行,但它似乎已经在主线程上运行......我怀疑这是从内部调用的实际请求getCurrentClient
在后台运行:
- (void)getCurrentClient:(void (^)(BOOL completed, NSDictionary *account))completion
{
__block BOOL operationSuccessful = NO;
__block NSDictionary *currentClient = nil;
NXOAuth2Account *currentAccount = [[[NXOAuth2AccountStore sharedStore] accounts] lastObject];
[NXOAuth2Request performMethod:@"GET"
onResource:[NSURL URLWithString:[NSString stringWithFormat:@"%@/clients/%@", kCatapultHost, currentAccount.userData[@"account_name"]]]
usingParameters:nil
withAccount:currentAccount
sendProgressHandler:nil
responseHandler:^ (NSURLResponse *response, NSData *responseData, NSError *error) {
if (error != nil) {
operationSuccessful = NO;
#if DEBUG
NSLog(@"ERROR: %@", error);
#endif
}
else {
operationSuccessful = YES;
NSError *jsonError;
currentClient = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&jsonError];
if (jsonError != nil) {
operationSuccessful = NO;
#if DEBUG
NSLog(@"Error: %@", jsonError);
#endif
}
}
completion(operationSuccessful, currentClient);
}];
}
那么我的方法(调用 reloadData)是好方法吗?没有办法让表格视图控制器等待请求完成吗?