【发布时间】:2012-08-09 15:41:42
【问题描述】:
尝试在 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];
}
【问题讨论】:
-
显示错误。此外,展示如何将 JSON 转换为 NSDictionary 以及如何提取数组
Menu。在调试器中检查Menu以确保它是一个 NSArray 并且它的内容是您所期望的。我怀疑 Menu 不是一个数组,即使您在声明中键入它也是一个数组。 -
发送到实例的无法识别的选择器
-
男人:什么选择器?它被称为什么类?
-
[_NSCDictionary objectAtIndex:] 无法识别的选择器发送到实例
标签: objective-c ios json uitableview