2012-07-06 3 views
0

J'essaie de créer ma première application iOS qui analyse json à partir d'un service Web.Analyse de json string dans iOS Objectif C

Dans mon .h je crée un tableau

NSArray *items; 

Dans mon fichier .m j'appelle le site Web et stocker les données dans le tableau. Tout va bien, sauf finalement j'essaie d'afficher les données dans un uitableview.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"ItemsCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    NSLog(@"%@",items); 

    NSDictionary *item = [items objectAtIndex:indexPath.row]; 
    NSString *title = [item objectForKey:@"title"]; 

    cell.title.text = title; 

    return cell; 
} 

Le NSLog des articles produit:

{ 
category = code; 
keyword = ""; 
limit = 20; 
lowPrice = ""; 
page = 0; 
products =  (
    { 
     description = "..."; 
     mobileFriendly = 1; 
     popularity = 2021; 
     productId = code; 
     title = "title"; 
    }, and so on... 
) 

Je reçois une erreur en essayant de faire NSDictionary * item = [Eléments objectAtIndex: indexPath.row]; Il dit faire objectAtIndex: indexPath.row est invalide.

Qu'est-ce que je fais mal?

Merci pour votre aide!

Répondre

0

La valeur stockée dans items est une instance de NSDictionary, mais vous lui envoyez un message NSArray. En outre, le code que vous avez publié fait référence à gift et ignore l'élément de toute façon.

Le tableau que vous cherchez est stocké sous la products clé dans le dictionnaire items, donc vous devez faire quelque chose comme ceci:

NSArray *products = [items objectForKey:@"products"]; 

NSDictionary *product = [products objectAtIndex:indexPath.row]; 
// Then use the product, instead of using 'gift' (whatever that is). 
NSString *title = [product objectForKey:@"title"]; 
+0

super merci! – Stephen

0

articles n'est pas un NSArray - il s'agit d'un NSDictionary. donc il n'a pas de méthode objectAtIndexPath:.

+0

donc si je change le fichier d'en-tête pour être NSDictionary articles * ... comment pourrais-je accéder aux produits? Merci! – Stephen