2012-04-19 76 views
0

我打算將iOS SDK中的NSDictionary *對象轉換爲NSString *。[iOS] [objC]無法將NSDictionary中的值轉換爲NSString

比方說我的NSDictionary對象還具有以下鍵值對: {「APS」:{「徽章」:9,「警告」:「你好」}}(注意值本身是一個的NSDictionary對象) 和我希望它轉換成帶有鍵值對的哈希映射爲{「aps」:「badge:9,alert:hello」}(注意值只是一個字符串)。

我可以使用下面的代碼打印在NSDictionary中的值:

NSDictionary *userInfo; //it is passed as an argument and contains the string I mentioned above 
for (id key in userInfo) 
{ 
    NSString* value = [userInfo valueForKey:key]; 
    funct([value UTF9String]; // my function 
} 

,但我沒能像打電話值UTT8String對象上任何的NSString方法。它給了我錯誤「終止應用程序由於未捕獲的異常NSInvalidArgumentException:原因[_NSCFDictionary UTF8String]:無法識別的選擇器發送到實例

+0

當你嘗試時會發生什麼? – borrrden 2012-04-19 05:53:38

+0

它使我的錯誤「終止應用程序由於未捕獲的異常NSInvalidArgumentException:原因[_NSCFDictionary UTF8字符串]:發送到實例 – 2012-04-19 05:57:25

+1

無法識別的選擇聽起來就像是一個嵌套的字典 – danielbeard 2012-04-19 05:57:52

回答

0

我找到了最簡單的方法。調用NSDictionary對象的描述方法給了我我需要的東西。愚蠢的錯過了第一次去。

1

您將不得不遞歸處理字典結構,這裏是一個例子,你應該能夠適應:

-(void)processParsedObject:(id)object{ 
    [self processParsedObject:object depth:0 parent:nil]; 
} 

-(void)processParsedObject:(id)object depth:(int)depth parent:(id)parent{ 

    if([object isKindOfClass:[NSDictionary class]]){ 

     for(NSString * key in [object allKeys]){ 
     id child = [object objectForKey:key]; 
     [self processParsedObject:child depth:depth+1 parent:object]; 
     }       


    }else if([object isKindOfClass:[NSArray class]]){ 

     for(id child in object){ 
     [self processParsedObject:child depth:depth+1 parent:object]; 
     } 

    } 
    else{ 
     //This object is not a container you might be interested in it's value 
     NSLog(@"Node: %@ depth: %d",[object description],depth); 
    } 


} 
+0

似乎也工作! – 2012-04-23 10:43:38

0

您需要在循環應用到每個孩子,而不是主詞典你自己說你有一個字典詞典:

for(id key in userInfo) 
{ 
    NSDictionary *subDict = [userInfo valueForKey:key]; 
    for(id subKey in subDict) 
    { 
     NSString* value = [subDict valueForKey:subKey]; 
    } 
} 

這個循環假設你擁有整個dicti第一級的onary,否則你需要使用danielbeard的遞歸方法。

相關問題