Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/119.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
IOS/Objective-c:使用长度为的字符串测试null_Ios_Objective C_Null - Fatal编程技术网

IOS/Objective-c:使用长度为的字符串测试null

IOS/Objective-c:使用长度为的字符串测试null,ios,objective-c,null,Ios,Objective C,Null,我试图测试对象中的空值,但以下代码引发错误:NSInvalidArgumentException',原因:'-[NSNull-length]:未识别的选择器发送到实例0x3b4a2a70'。 NSString *pic =item.pic;//this is the value for pic in object. Pic is a string. if ([pic length]) { //do something if pic is not null } 下面是如何

我试图测试对象中的空值,但以下代码引发错误:
NSInvalidArgumentException',原因:'-[NSNull-length]:未识别的选择器发送到实例0x3b4a2a70'。

NSString *pic =item.pic;//this is the value for pic in object.  Pic is a string.
if ([pic length]) {
           //do something if pic is not null
}
下面是如何在item对象中声明pic:

@property (nonatomic, strong) NSString *pic;
如果您能提供任何建议,说明这样做的对错之处。

请简单介绍

if (pic) {
    // do something if pic is not null
}
您的代码不工作,因为
NSNull
显然没有长度


但是这里真正的问题是,如果
pic
NSString
,那么您的代码就可以工作了。在这种情况下,它不是,而是
NSNull
。检查
项的返回类型。pic

您可以检查对象的
类的种类

NSString *pic =item.pic;//this is the value for pic in object.  Pic is a string.
if (![pic isKindOfClass:[NSNull class]]) {
           //do something if pic is not null
}

以下内容将很好地工作-

NSString *pic =item.pic;
if (pic) {
   if ([pic length]) {
      //Do some stuff
   }
}

您正在运行一个显式的
NSNull
实例,该实例在SDK中的不同位置使用。我在处理JSON值时经常看到它。在JSON正文中,如果存在显式空值,则会将其转换为
[NSNull null]
。您看到的错误表明您正在将消息
length
发送到一个
NSNull
实例,该实例无效

在调用length之前,您需要检查
NSNull

if(![pic isEqual:[NSNull null]] && [pic length] > 0) {
    // Do something
}

我认为字符串长度的全部意义在于,如果它为null,它将没有长度,并返回false。。。尝试更改它,但出现另一个错误:属性的值类型不可接受:property=“pic”;所需类型=NSString;给定类型=NSNull;value=。'您可以对nil值调用length。你不能在NSNull值上调用它,NSNull值是一个显式表示null的对象类型。我认为你遇到了{![pic Iskindof类…通过这次调整,它成功了。谢谢!请在发布前搜索-