How can I check if an object in an NSArray is NSNull?

后端 未结 9 1841
忘了有多久
忘了有多久 2020-12-23 18:50

I am getting an array with null value. Please check the structure of my array below:

 (
    \"< null>\"
 )

When I\'m trying to access

9条回答
  •  猫巷女王i
    2020-12-23 19:27

    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: ()"
    

    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

提交回复
热议问题