-4

JSON ファイルを TableView に表示しようとすると、エラーが発生します。

これは私の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];
}
4

2 に答える 2

1

objectAtIndex は NSArray のメソッドです。Menu オブジェクトは NSDictionary です。次のように、メニュー ディクショナリ内で配列を取得する必要があります。

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

行のソースとして myArray を使用します。

于 2012-08-09T16:28:16.623 に答える
0

NSDictionary は objectAtIndex メソッドに応答しません。ディクショナリのすべての値の配列を取得できますが、これは特定の方法で順序付けられておらず、呼び出しによって異なる場合があります。セルの値を使用してデータ ソース配列を定義し、それらの値を使用して辞書の情報にアクセスする必要があります。

于 2012-08-09T15:49:34.400 に答える