我是 iOS 开发的新手,我正在尝试找出解决我的问题的最佳方法。我有一个 UITableViewController
类,它在 viewDidLoad
中调用一个名为 fetchModules
的方法。这会使用 AFNetworking 2 获取我的表所需的所有数据。
但是,我的表委托(delegate)方法(例如 numberOfRowsInSection
和 cellForRowAtIndexPath
)失败了,因为 AFNetworking 调用尚未完成并且我用来存储数据的数组还没有完成已填充。
我得到的实际错误是
Terminating app due to uncaught exception 'NSRangeException'
这是我的代码:
#import "HistoryTableViewController.h"
@interface HistoryTableViewController ()
@property NSArray *modules;
@end
@implementation HistoryTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.modules = [[NSArray alloc] init];
[self fetchModules];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)fetchModules
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:self.token forHTTPHeaderField:@"X-Auth-Token"];
[manager GET:@"http://myurl.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
//NSLog(@"JSON: %@", responseObject);
self.modules = [responseObject objectForKey:@"data"];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.modules && self.modules.count) {
return self.modules.count;
} else {
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = @"Cell Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}
NSDictionary *module = [self.modules objectAtIndex:indexPath.row];
cell.textLabel.text = [module objectForKey:@"code"];
return cell;
}
建议?
最佳答案
这是非常常见的异步网络调用解决方案。
在AFNetworking
成功 block
中添加[self.tableView reloadData]
:
- (void)fetchModules
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:self.token forHTTPHeaderField:@"X-Auth-Token"];
[manager GET:@"http://myurl.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
//NSLog(@"JSON: %@", responseObject);
self.modules = [responseObject objectForKey:@"data"];
[self.tableView reloadData];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}`enter code here`
关于ios - TableView 和 AFNetworking 异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24550836/