I’m getting an error when trying to display a JSON file in a TableView.
this is my JSON File:
{
"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"
}
]
}
This is my code in 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;
}
The error occurs here;
NSDictionary *menuItem = [Menu objectAtIndex:indexPath.row];
I’m new to iOS 5, and I’m not sure if the first line of the JSON file (“GetMenuMethodResult”: [) is causing this error:
**[_NSCDictionary objectAtIndex:] unrecognized selector sent to instance**
Rest of the code:
@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];
}
objectAtIndex is a method for NSArray. Your Menu object is an NSDictionary. You need to get the array within the Menu dictionary like this:
and use myArray as the source for your rows.