2011-11-09 57 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,價格和別名...

有人知道該怎麼做嗎?

謝謝,請原諒我的壞英語!

+0

看起來你有嵌套字典。使用[[dic objectForKey:@「response」] objectForKey:@「products」],下一個可能是一個字典數組,我不知道,每個步驟都有一定的耐心和NSLog。 – Jano

回答

1

開始與

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

你可以做這樣的事情:

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 
} 

我有過類似的情況下,到這個(解析JSON)數組不是返回一個signle值,所以必須檢查一個數組(您的案例中的產品字典)或單個NSDictionary(您的案例中的產品字典)的結果。

+0

謝謝Jim ...完美地工作! 我不知道它會返回一個NSDictionary,當它是一個單一的結果,它會返回NSArray(特別是一個NSDictionarys數組),當它是很多結果... 再次感謝! – leoromerbric

22
NSArray* keys = [theDict allKeys]; 

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

    // do what needed with obj 
} 

你可以嘗試這樣的事:

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上有一個方法,它返回一個包含字典值的新數組。也許這會有所幫助。

相關問題