如果为nil或<null>则为例外

sav*_*oob 0 cocoa-touch objective-c iphone-sdk-3.0

我从php脚本中提取图片的位置,如果没有图片位置,它会在JSON输出中显示"null".这在我的代码中抛出异常.这是不起作用的代码:

    NSString *piclocation = picloc;
if(piclocation == nil || @"null"){

}else{
NSString *mutableUrlString = @"https://www.mypage.com/uploads";
mutableUrlString = [mutableUrlString stringByAppendingString: piclocation];
NSLog(mutableUrlString);
NSURL *url = [NSURL URLWithString: mutableUrlString];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
imageView.image = image;
}
Run Code Online (Sandbox Code Playgroud)

错误是:由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' * - [NSNull length]:无法识别的选择器发送到实例0x98d5a0'任何建议?

Sye*_*idi 9

你需要纠正你的代码一点点.

if (piclocation == (id)[NSNull null] || piclocation.length == 0 || [piclocation isEqualToString:@"null"] )
Run Code Online (Sandbox Code Playgroud)

我想这会为你做到.