这是我的代码(我需要从远程服务器上的源解析多个 JSON 文件),我需要使用每个解析的 SINGLE 值填充 UITableView:
单个 JSON 源(简单),位于 h**p://WWW.REMOTESERVERWITHJSONSOURCE.NET/A1:
{
"id": 0001,
"main": {
"main1A": 100,
},
"main2": {
"main2A": 200,
},
"url": "http...",
}
分配并初始化我的数组:
- (void)viewDidLoad {
// other stuff
arrayA = [[NSMutableArray alloc] initWithObjects:@"A1", @"A2", nil]; //each object A1, A2...An is the single JSON source I need to parse
arrayB = [[NSMutableArray alloc] initWithObjects:@"B1", @"B2", nil];
}
解析方法:
- (void)LoadParse {
main = [[NSMutableArray alloc] init];
main2 = [[NSMutableArray alloc] init];
for (int i=0; i < [arrayA count]; i++) {
NSURL *url = [NSURL URLWithString:
[NSString stringWithFormat:
@"http://WWW.REMOTESERVERWITHJSONSOURCE.NET/%@",[arrayA objectAtIndex:i]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSMutableDictionary *arrayMain = [JSON valueForKey:@"main"];
[main addObject:[arrayMain objectForKey:@"main1A"]];
NSMutableDictionary *arrayMain2 = [JSON valueForKey:@"main2"];
[main2 addObject:[arrayMain2 objectForKey:@"main2A"]];
[table reloadData];
[table scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
}];
[operation start];
}
}
UITableView 方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arrayA count];
}
// 其他方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
}
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.detailTextLabel.font = [UIFont systemFontOfSize:11];
cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@",[main objectAtIndex:indexPath.row],[main2 objectAtIndex:indexPath.row]]; // here I get error 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
return cell;
}
错误:当我在arrayA中只分配和初始化一个对象时,没关系:UITableView填充一行并获取main1和main2的值;如果我在 arrayA 中分配并初始化多个对象,就像在这个例子中一样,应用程序崩溃并出现错误信号 SIGABRT:'NSRangeException',原因:' * -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' ... 怎么了?请帮我找麻烦,谢谢!