JSON到UITableView错误

问题描述:

当我试图在TableView中显示JSON文件时出现错误。JSON到UITableView错误

这是我的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]; 
} 
+0

什么是错误? – Dustin 2012-08-09 15:54:49

+1

显示错误。另外,请说明如何将JSON转换为NSDictionary,以及如何提取数组'Menu'。在调试器中检查'Menu'以确保它是一个NSArray,并且它的内容是你所期望的。我怀疑菜单不是一个数组,即使您在声明中键入它也是一个数组。 – Jim 2012-08-09 16:03:13

+0

发送到实例的无法识别的选择器 – BulletRocks 2012-08-09 16:05:57

objectAtIndex是NSArray的一种方法。你的Menu对象是一个NSDictionary。您需要像这样获取菜单字典中的数组:

NSArray *myArray = [Menu objectForKey:@"GetMenuMethodResult"]; 

并使用myArray作为行的源。

+0

谢谢吉姆这样做的伎俩 – BulletRocks 2012-08-10 14:14:03

NSDictionary不响应objectAtIndex方法。您可以获取字典的所有值数组,但不以任何特定方式排序,并且可能因呼叫而异。您需要使用单元格的值定义数据源数组,并使用这些值访问字典的信息。