2012-08-09 33 views
-4

當我試圖在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

回答

1

objectAtIndex是NSArray的一種方法。你的Menu對象是一個NSDictionary。您需要像這樣獲取菜單字典中的數組:

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

並使用myArray作爲行的源。

+0

謝謝吉姆這樣做的伎倆 – BulletRocks 2012-08-10 14:14:03

0

NSDictionary不響應objectAtIndex方法。您可以獲取字典的所有值數組,但不以任何特定方式排序,並且可能因呼叫而異。您需要使用單元格的值定義數據源數組,並使用這些值訪問字典的信息。