How can I check if an object in an NSArray is NSNu

2020-02-17 04:01发布

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

-[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

9条回答
戒情不戒烟
2楼-- · 2020-02-17 04:46
if (myArray != (id)[NSNull null])

OR

if(![myArray isKindOfClass:[NSNull class]]) 
查看更多
祖国的老花朵
3楼-- · 2020-02-17 04:46

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:

Using 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 *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.

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"

Taken from https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html

查看更多
在下西门庆
4楼-- · 2020-02-17 04:56

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"])) ...
查看更多
登录 后发表回答