2011-11-09 8 views
3

私は問題があります。どのようにNSDictionaryのすべての値を反復して取得できますか?

XMLReaderクラスを使用してNSDictionaryを取得していますが、すべて正常に動作します。しかし、私は私のproductData要素の属性の値を取得することはできません。

具体的には、私はNSDictionaryを次ています

{ 
response = { 
    products = { 
    productsData = (
    { 
    alias = "Product 1"; 
    id = 01; 
    price = "10"; 
    }, 
    { 
    alias = "Product 2"; 
    id = 02; 
    price = "20"; 
    }, 
    { 
    alias = "Product 3"; 
    id = 03; 
    price = "30"; 
    }); 
}; 
}; 
} 

私はNSDictionaryデ作成するには、このコードを使用:

NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError]; 

とresponseDataが含まれています

<application> 
    <products> 
    <productData> 
     <id>01</id> 
     <price>10</price> 
     <alias>Product 1</alias> 
    </productData> 
    <productData> 
     <id>02</id> 
     <price>20</price> 
     <alias>Product 2</alias> 
    </productData> 
    <productData> 
     <id>02</id> 
     <price>20</price> 
     <alias>Product 3</alias> 
    </productData> 
    </products> 
</application> 

その後、私ドンid、price、aliasなどの各productDataの値を取得する方法を知っていない...

誰でも方法を知っていますか?

ありがとう、私の悪い英語を許してください!

+0

ネストされた辞書があるようです。 [[dic objectForKey:@ "response"] objectForKey:@ "products"]を使用すると、次の文字列は辞書の配列になるかもしれませんが、わかりません。 – Jano

答えて

1

を配列がないJSONの解析signle値のために返されたので、配列(あなたのケースの製品辞書の配列)または単一のNSDictionary(あなたのケースではプロダクト辞書)の両方を調べる必要がありました。

+0

Thanks Jim ...完璧に動作します! 単一の結果だったときにNSDictionaryが返されることはわかりませんでした。多くの結果が得られたときにNSArray(特にNSDictionaryの配列)が返されました... もう一度ありがとう! – leoromerbric

22
NSArray* keys = [theDict allKeys]; 

for(NSString* key in keys) { 
    id obj = [theDict objectForKey:key]; 

    // do what needed with obj 
} 

あなたはこのような何かを試みることができる:私は同様のケースがあった

NSDictionary *application = [dictionary objectForKey:@"application"]; 
if ([[application objectForKey:@"products"] isKindOfClass [NSArray class]]) { 
    NSArray *products = [application objectForKey:@"products"]; 
    for (NSDictionary *aProduct in products) { 
     // do something with the contents of the aProduct dictionary 
    } 
else if {[[application objectForKey:@"products"] isKindOfClass [NSDictionary class]]) { 
    // you will have to see what the returned results look like if there is only one product 
    // that is not in an array, but something along these lines may be necessary 
    // to get to a single product dictionary that is returned 
} 

:あなたはこのような何かを行うことができ

NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError]; 

を皮切り

NSArray* keys = [theDict allKeys]; 

for(NSString* key in keys) { 
    if ([key isEqualToString:@"product"]) { 
    NSArray* arr = [theDict objectForKey:key]; 

    // do what needed with arr 
} 
    } 
+1

ありがとうございました:)ちょうど '[key isEqualToString @" product "]'は[key isEqualToString:@ "product"] 'でなければなりません** ** ** – Sawsan

4

NSDictionary--allValuesには、辞書の値を含む新しい配列を返すメソッドがあります。多分それが助けになるでしょう。

関連する問題