我想用 JSON 数据(已经过验证)填充主从应用程序,并且收到错误“未捕获的异常 __NSCFDictionary objectAtIndexedSubscript”。非常感谢。
JSON 文件:
{
"Name": [
"Entry 1 (Comment1) (Comment1b)",
"Entry 2 (Comment2) ",
"Entry 3 (Comment3) ",
"Entry 4 (Comment4) (Comment4b)"
],
"URLs": [
"http://www.myurl.com/%20(Comment1)%20(Comment1b)",
"http://www.myurl.com/%20(Comment2)%20(Comment2b)",
"http://www.myurl.com/%20(Comment3)%20(Comment3b)",
"http://www.myurl.com/%20(Comment4)%20(Comment4b)"
]
}
这就是我加载 JSON 文件的方式:
@interface MasterViewController () {
NSArray *_objects;
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://myurl.com/Data.json"];
NSData *data = [NSData dataWithContentsOfURL:url];
_objects = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
这就是我解析它的方式:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSLog(@"_objects contains: %@", _objects);
// # This following line creates the error:
NSDictionary *object = _objects [indexPath.row];
NSLog(@"object contains: %@", object);
cell.textLabel.text = [object objectForKey: @"Name"];
cell.detailTextLabel.text = [object objectForKey: @"URLs"];
return cell;
}