我遇到了最奇怪的問題。我使用下面的代碼來顯示登錄用戶的個人資料照片(我正在從Drupal數據庫的字段中檢索圖像)。即使使用if/else語句,空值也會導致崩潰?
.M
//USER PHOTO
NSDictionary *user = [[DIOSSession sharedSession] user];
NSString *secondLink = user[@"field_photo_path"][@"und"][0][@"safe_value"];
NSLog(@"This is second link %@", secondLink);
if([secondLink length]>0) {
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
// self.imageView.image = [UIImage imageWithData:imageData];
self.imageView.image = [[UIImage alloc] initWithData:imageData];
} else {
NSString *ImageURL = @"http://url.com/default.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
}
當然,如果是secondlink爲空(或空的,例如沒有照片已上傳),我收到以下錯誤:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArray0 objectForKeyedSubscript:]: unrecognized selector sent to instance 0x14f602fe0'
我想我解決這個問題與if/else語句,但顯然不是。我怎樣才能解決這個問題?
乾杯!
哪條線是崩潰?基於這個消息,它看起來像是在'NSString * secondLink = ...'行和你使用的一箇中間值,就像它是一個字典實際上是一個數組。 – dan
@dan NSString * secondLink = user [@「field_photo_path」] [@「und」] [0] [@「safe_value」]; - 這是崩潰的行,但只有當field_photo_path爲空時才行。當它是空的時候,我需要它不會崩潰。 – Brittany
它不會崩潰,如果它是空的東西那裏包含你不期望的東西。我建議你使用變量來訪問所有的東西,這樣你就有機會調試它。 – gnasher729