我是iOS新手,我試圖弄清楚我的問題最好的解決方案是什麼。我有一個UITableViewController
類,它在viewDidLoad
中調用名爲fetchModules
的方法。這使用AFNetworking 2獲取我需要的所有數據。表視圖和AFNetworking異步調用
但是,我的表委託方法(如numberOfRowsInSection
和cellForRowAtIndexPath
)失敗,因爲AFNetworking調用尚未完成,並且我正在使用的數組存儲數據沒有被填充。
我得到實際的錯誤是
終止應用程序由於未捕獲的異常 '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;
}
建議?
同樣的問題與我... –