2012-01-16 61 views
2

我通過蘋果從這裏http://bit.ly/x4nhG5錯誤呼籲的NSDictionary方含allKeys當JSON對象

顯示Twitter的飼料從示例代碼示例工作,代碼走的是JSON,並把它變成一個NSDictionary:

 NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError]; 

我只是想在這一點上做的是看看所有的回來做這個鍵:

NSArray *allKeysArray = [publicTimeline allKeys]; 

我再接收地e嘗試運行程序時發生錯誤:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray allKeys]: unrecognized selector sent to instance 0x6a950f0'

爲什麼從JSON加載的NSDictionary的行爲如此?

感謝, 舊貨

回答

13

如果你看你看'-[__NSCFArray allKeys]異常,這表明你確實有一個__NSCFArray這是NSArray私有子類。這不是NSDictionary,這就是您獲得例外的原因。


如果看看JSON給它的形式是

[        
    { 
     coordinates: null, 
     truncated: false, 
     // ... 
    }, 
    { 
     coordinates: null, 
     truncated: false, 
     // ... 
    } 
]        

JSON[]表示一個數組和{}表示對象。

An [JSON] array is an ordered collection of values

這意味着JSON陣列可以容易地映射到NSArray

An [JSON] object is an unordered set of name/value pairs

這意味着JSON對象可以映射到NSDictionary


所以看着飼料,我們可以看到,我們實際上有一個對象數組。其中NSJSONSerialization將變成NSDictionaryNSArray's。因此,要找到字典,我們首先需要從數組中首先訪問它,結果如下:

NSDictionary *tweet = [publicTimeline objectAtIndex:0]; 

NSArray *allKeys = [tweet allKeys]; 
+1

謝謝保羅。 Apple在他們的代碼中將* publicTimeLine作爲一個NSDictionary進行了delcaring。爲了使用你的建議;我不得不將* publicTimeLine聲明爲NSArray。 通過這樣做:NSArray * publicTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError]; 我能夠使用你的例子。 謝謝! – Flea 2012-01-16 20:31:50

+1

'NSDIctionary可能不會響應objectAtIndex'問題。爲什麼?。我正在使用iOS 6。 – 2014-04-21 14:04:25

1

什麼錯誤告訴你的是,你的publicTimeline不是NSDictionaryNSArray

所以,我的猜測是不是

NSArray *allKeysArray = [publicTimeline allKeys]; 

,你打算這會工作。

NSArray *allKeysArray = [[publicTimeline objectAtIndex:0] allKeys]; 
+1

大麥,NSDictionary不包含objectAtIndex的方法。你會有另外一個建議嗎? – Flea 2012-01-16 19:46:33