尝试在 TableView 中显示 JSON 文件时出现错误。
这是我的 JSON 文件:
{
"GetMenuMethodResult": [
{
"itemDescription": "Description",
"itemNumber": 501,
"itemPrice": 6,
"itemTitle": "Item1"
},
{
"itemDescription": "Description",
"itemNumber": 502,
"itemPrice": 6.35,
"itemTitle": "Item2"
},
{
"itemDescription": "Description",
"itemNumber": 503,
"itemPrice": 5.55,
"itemTitle": "item 3"
}
]
}
这是我在 Xcode 中的代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return Menu.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *menuItem = [Menu objectAtIndex:indexPath.row]; <- error occurs here
NSString *itemName = [menuItem objectForKey:@"itemTitle"];
NSString *itemDesc = [[menuItem objectForKey:@"itemDescription"];
cell.textLabel.text = itemName;
cell.detailTextLabel.text =itemDesc ;
return cell;
}
错误发生在这里;
NSDictionary *menuItem = [Menu objectAtIndex:indexPath.row];
我是 iOS 5 的新手,我不确定 JSON 文件的第一行 ("GetMenuMethodResult": [) 是否导致此错误:
**[_NSCDictionary objectAtIndex:] unrecognized selector sent to instance**
其余代码:
@interface MasterViewController : UITableViewController {
NSArray *Menu;
}
- (void)fetchMenu;
@end
- (void)fetchMenu
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: @"http://"]];
NSError* error;
Menu = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchMenu];
}