我遇到了最奇怪的问题。我使用下面的代码来显示登录用户的个人资料照片(我正在从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