2011-11-09 2 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의 값을 얻는 방법을 알지 못합니다. ...

아무도 어떻게 해야할지 알고 ??

감사합니다. 내 나쁜 영어를 용서해주세요.

NSArray* keys = [theDict allKeys]; 

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

    // do what needed with arr 
} 
    } 
+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 
} 

+0

]이 있어야합니다. [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 
} 

이 뭔가를 시도 할 수 배열에없는 JSON 구문 분석 signle 값으로 반환되었으므로 결과는 배열 (귀하의 경우 제품 사전) 또는 단일 NSDictionary (귀하의 경우에는 제품 사전) 모두에 대해 검사해야합니다.

+1

답변 해 주셔서 감사합니다 :). ** [** key isEqualToString : @ "product"]'** [** – Sawsan

4

NSDictionary--allValues에는 사전 값이 포함 된 새 배열을 반환하는 메서드가 있습니다. 도움이 될지도 몰라.

관련 문제