2013-01-31 126 views
0

試圖獲得一個標籤,以顯示一些JSON拉數據...將NSArray轉換爲NSString崩潰?

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
    { 
     NSError *myError = nil; 
     NSDictionary *res = [NSJSONSerialization JSONObjectWithData:jsonresponse   options:NSJSONReadingMutableLeaves error:&myError]; 
     NSArray *results = [res objectForKey:@"current_observation"]; 
     NSArray *cur = [results valueForKey:@"weather"]; 
     NSArray *tmp = [results valueForKey:@"temp_f"]; 
     NSString * tmpstring = [[tmp valueForKey:@"description"] componentsJoinedByString:@""]; 
     temp.text = tmpstring; 
    } 

當它運行的代碼,它吐出了這一點...

2013-01-31 15:38:03.319 Places[4659:907] -[__NSCFString componentsJoinedByString:]: unrecognized selector sent to instance 0x5680d0 
2013-01-31 15:38:03.321 Places[4659:907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString componentsJoinedByString:]: unrecognized selector sent to instance 0x5680d0' 
*** First throw call stack: 
(0x32b3e3e7 0x3a82f963 0x32b41f31 0x32b4064d 0x32a98208 0x413b 0x3347a915 0x333ba769 0x333ba685 0x3281b64f 0x3281ad33 0x32843013 0x32a84acd 0x32843473 0x327a7461 0x32b138f7 0x32b1315d 0x32b11f2f 0x32a8523d 0x32a850c9 0x3666333b 0x349a12b9 0x20c9 0x2050) 
libc++abi.dylib: terminate called throwing an exception 
(lldb) 

任何想法?

+1

驗證你確定'[TMP valueForKey:@「說明」]'返回一個NSArray,它,而長相好像它返回一個NSString的錯誤信息msg – tttthomasssss

回答

2

-description是從NSObject和NSObject協議的一部分繼承的方法;它返回一個NSString *以及對象的一些描述。所有類都可以覆蓋它以返回任意的NSString。

-valueForKey:將返回一個數組,其中包含對所有對象調用-description方法的結果。這似乎不是這種情況,因爲[tmp valueForKey:@"description"]似乎返回NSString *而不是數組。我猜tmp不是一個數組,因此你的應用程序崩潰。

不知道JSON數據實際上是什麼,這裏不可能說出什麼問題。請用一些示例數據更新您的問題。

+0

它說:「沒有可見@interface爲NSArray聲明選擇器'objectForKey:'」 –

+0

哦,我看到好了然後.. –

+0

哦,好吧,我沒有注意到你打電話'tmp'數組上的'-valueForKey:'。你認爲這個代碼應該做什麼?我不明白。我假設你打算查詢字典中與「@」描述「鍵關聯的對象。如果這是正確的,將它改爲'[[res objectForKey:@「description」] componentsJoinedByString:@「」];' –

0

description爲從NSObject繼承的所有對象返回一個NSString。 NSString和它的祖先都不實現組件JoinedByString。 如果你想使用componentsJoinedByString你需要直接發送到NSArray或實現該方法的其他集合對象。 在Objective-C中嵌套消息傳遞時,需要確定返回的對象類是什麼。如果你不確定,那麼你的消息就會變得非常緊張,所以你會看到它是什麼。 如果你不能在某些情況下可以肯定,這是更好地UNNEST消息,並使用一些方法像

if ([object respondsToSelector:@selector(someSelector:)]) { 
    // do stuff here 
} else { 
    // some alternative 
}