ios 如何检查 NSArray 中的对象是否为 NSNull?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19059202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if an object in an NSArray is NSNull?
提问by Navi
I am getting an array with null value. Please check the structure of my array below:
我得到一个空值数组。请在下面检查我的数组的结构:
(
"< null>"
)
When I'm trying to access index 0 its crashing because of
当我尝试访问索引 0 时它崩溃了
-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70
Currently its crashing because of that array with a crash log:
目前它的崩溃是因为该数组带有崩溃日志:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70'
*** First throw call stack:
(0x2d9fdf53 0x3820a6af 0x2da018e7 0x2da001d3 0x2d94f598 0x1dee57 0x1dfd31 0x302f598d 0x301a03e3 0x3052aeed 0x3016728b 0x301659d3 0x3019ec41 0x3019e5e7 0x30173a25 0x30172221 0x2d9c918b 0x2d9c865b 0x2d9c6e4f 0x2d931ce7 0x2d931acb 0x3262c283 0x301d3a41 0xabb71 0xabaf8)
libc++abi.dylib: terminating with uncaught exception of type NSException
回答by Charith Nidarsha
id object = myArray[0];// similar to [myArray objectAtIndex:0]
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
回答by Toni Albuquerque
if (myArray != (id)[NSNull null])
OR
或者
if(![myArray isKindOfClass:[NSNull class]])
回答by respectTheCode
Building off of Toni's answer I made a macro.
基于托尼的回答,我做了一个宏。
#define isNSNull(value) [value isKindOfClass:[NSNull class]]
Then to use it
然后使用它
if (isNSNull(dict[@"key"])) ...
回答by Alex Zavatone
Awww, guys. This is an easy one.
哇,伙计们。这是个简单的。
// if no null values have been returned.
if ([myValue class] == [NSNull class]) {
myValue = nil;
}
I'm sure there are better answers, but this one works.
我相信有更好的答案,但这个有效。
回答by Jasper Blues
I found the code for working with NSNull
has the following problems:
我发现使用的代码NSNull
有以下问题:
- Looks noisy and ugly.
- Time consuming.
- Error prone.
- 看起来又吵又丑。
- 耗时。
- 容易出错。
So I created the following category:
所以我创建了以下类别:
@interface NSObject (NSNullUnwrapping)
/**
* Unwraps NSNull to nil, if the object is NSNull, otherwise returns the object.
*/
- (id)zz_valueOrNil;
@end
With the implementation:
随着实施:
@implementation NSObject (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return self;
}
@end
@implementation NSNull (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return nil;
}
@end
It works by the following rules:
它按照以下规则工作:
- If a category is declared twice for the same
Class
(ie singleton instance of theClass
type) then behavior is undefined. However, a method declared in a subclass is allowed to override a category method in its super-class.
- 如果为同一个类别声明了两次
Class
(即该Class
类型的单例实例),则行为未定义。但是,允许在子类中声明的方法覆盖其超类中的类别方法。
This allows for more terse code:
这允许更简洁的代码:
[site setValue:[resultSet[@"main_contact"] zz_valueOrNil] forKey:@"mainContact"];
. . as opposed to having extra lines to check for NSNull
. The zz_
prefix looks a little ugly but is there for safety to avoid namespace collisions.
. . 而不是有额外的行来检查NSNull
. 该zz_
前缀看起来有点丑,但那里的安全,以避免命名空间冲突。
回答by Hermann Klecker
A lot of good and interesting answers have been given already and (nealry) all of them work.
已经给出了很多好的和有趣的答案,并且(几乎)所有答案都有效。
Just for completion (and the fun of it):
只是为了完成(以及它的乐趣):
[NSNull null] is documented to return a singleton. Therefore
[NSNull null] 被记录为返回单例。所以
if (ob == [NSNull null]) {...}
works fine too.
工作正常。
However, as this is an exception I don't think that using == for comparing objects is a good idea in general. (If I'd review your code, I'd certainly comment on this).
但是,由于这是一个例外,我认为使用 == 比较对象一般不是一个好主意。(如果我要查看您的代码,我肯定会对此发表评论)。
回答by Wayne
Consider this approach:
考虑这种方法:
Option 1:
选项1:
NSString *str = array[0];
if ( str != (id)[NSNull null] && str.length > 0 {
// you have a valid string.
}
Option 2:
选项 2:
NSString *str = array[0];
str = str == (id)[NSNull null]? nil : str;
if (str.length > 0) {
// you have a valid string.
}
回答by Marky
You can use the following check:
您可以使用以下检查:
if (myArray[0] != [NSNull null]) {
// Do your thing here
}
The reason for this can be found on Apple's official docs:
原因可以在 Apple 的官方文档中找到:
Using NSNull
使用 NSNull
The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary).
NSNull 类定义了一个单例对象,用于在 nil 被禁止作为值的情况下(通常在集合对象,例如数组或字典中)表示空值。
NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = @[nullValue];
NSLog(@"arrayWithNull: %@", arrayWithNull);
// Output: "arrayWithNull: (<null>)"
It is important to appreciate that the NSNull instance is semantically different from NO or false—these both represent a logical value; the NSNull instance represents the absence of a value. The NSNull instance is semantically equivalent to nil, however it is also important to appreciate that it is not equal to nil. To test for a null object value, you must therefore make a direct object comparison.
重要的是要意识到 NSNull 实例在语义上不同于 NO 或 false——它们都代表一个逻辑值;NSNull 实例表示没有值。NSNull 实例在语义上等同于 nil,但是理解它不等于 nil 也很重要。因此,要测试空对象值,您必须进行直接对象比较。
id aValue = [arrayWithNull objectAtIndex:0];
if (aValue == nil) {
NSLog(@"equals nil");
}
else if (aValue == [NSNull null]) {
NSLog(@"equals NSNull instance");
if ([aValue isEqual:nil]) {
NSLog(@"isEqual:nil");
}
}
// Output: "equals NSNull instance"
回答by JAL
In Swift (or bridging from Objective-C), it is possible to have NSNull
and nil
in an array of optionals. NSArray
s can only contain objects and will never have nil
, but may have NSNull
. A Swift array of Any?
types may contain nil
, however.
在夫特(或从目标C桥接),它有可能具有NSNull
和nil
在自选的阵列。 NSArray
s 只能包含对象,永远不会有nil
,但可能有NSNull
。然而,Any?
类型的 Swift 数组可能包含nil
。
let myArray: [Any?] = [nil, NSNull()] // [nil, {{NSObject}}], or [nil, <null>]
To check against NSNull
, use is
to check an object's type. This process is the same for Swift arrays and NSArray
objects:
要检查NSNull
,请用于is
检查对象的类型。这个过程对于 Swift 数组和NSArray
对象是一样的:
for obj in myArray {
if obj is NSNull {
// object is of type NSNull
} else {
// object is not of type NSNull
}
}
You can also use an if let
or guard
to check if your object can be casted to NSNull
:
您还可以使用if let
或guard
来检查您的对象是否可以转换为NSNull
:
guard let _ = obj as? NSNull else {
// obj is not NSNull
continue;
}
or
或者
if let _ = obj as? NSNull {
// obj is NSNull
}