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

后端 未结 9 1764
忘了有多久
忘了有多久 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条回答
  • 2020-12-23 19:33

    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

    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).

    0 讨论(0)
  • 2020-12-23 19:34

    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.

    0 讨论(0)
  • 2020-12-23 19:34

    In Swift (or bridging from Objective-C), it is possible to have NSNull and nil in an array of optionals. NSArrays can only contain objects and will never have nil, but may have NSNull. A Swift array of Any? types may contain nil, however.

    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:

    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:

    guard let _ = obj as? NSNull else {
        // obj is not NSNull
        continue;
    }
    

    or

    if let _ = obj as? NSNull {
        // obj is NSNull
    }
    
    0 讨论(0)
提交回复
热议问题