Detect a Null value in NSDictionary

2019-01-09 02:06发布

I have an NSDictionary that's populated from a JSON response from an API server. Sometimes the values for a key in this dictionary are Null

I am trying to take the given value and drop it into the detail text of a table cell for display.

The problem is that when I try to coerce the value into an NSString I get a crash, which I think is because I'm trying to coerce Null into a string.

What's the right way to do this?

What I want to do is something like this:

cell.detailTextLabel.text = sensor.objectForKey( "latestValue" ) as NSString

Here's an example of the Dictionary:

Printing description of sensor:
{
    "created_at" = "2012-10-10T22:19:50.501-07:00";
    desc = "<null>";
    id = 2;
    "latest_value" = "<null>";
    name = "AC Vent Temp";
    "sensor_type" = temp;
    slug = "ac-vent-temp";
    "updated_at" = "2013-11-17T15:34:27.495-07:00";
}

If I just need to wrap all of this in a conditional, that's fine. I just haven't been able to figure out what that conditional is. Back in the Objective-C world I would compare against [NSNull null] but that doesn't seem to be working in Swift.

标签: ios swift nsnull
6条回答
做自己的国王
2楼-- · 2019-01-09 02:38

NSNull is a class like any other. Thus you can use is or as to test an AnyObject reference against it.

Thus, here in one of my apps I have an NSArray where every entry is either a Card or NSNull (because you can't put nil in an NSArray). I fetch the NSArray as an Array and cycle through it, switching on which kind of object I get:

for card:AnyObject in arr {
    switch card { // how to test for different possible types
    case let card as NSNull:
        // do one thing
    case let card as Card:
        // do a different thing
    default:
        fatalError("unexpected object in card array") // should never happen!
    }
}

That is not identical to your scenario, but it is from a working app converted to Swift, and illustrates the full general technique.

查看更多
Melony?
3楼-- · 2019-01-09 02:43

I had a very similar problem and solved it with casting to the correct type of the original NSDictionary value. If your service returns a mixed type JSON object like this

{"id":2, "name":"AC Vent Temp", ...}

you'll have to fetch it's values like that.

var id:int = sensor.valueForKey("id") as Int;
var name:String? = sensor.valueForKey("name") as String;

This did solve my problem. See BAD_INSTRUCTION within swift closure

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-09 02:47

my solution for now:

func isNull(someObject: AnyObject?) -> Bool {
    guard let someObject = someObject else {
        return true
    }

    return (someObject is NSNull)
}

tests look good so far...

tests look good so far

查看更多
神经病院院长
5楼-- · 2019-01-09 02:57

I'm using those combination. Additionaly that combination checks if object is not "null".

func isNotNull(object:AnyObject?) -> Bool {
    guard let object = object else {
        return false
    }
    return (isNotNSNull(object) && isNotStringNull(object))
}

func isNotNSNull(object:AnyObject) -> Bool {
    return object.classForCoder != NSNull.classForCoder()
}

func isNotStringNull(object:AnyObject) -> Bool {
    if let object = object as? String where object.uppercaseString == "NULL" {
        return false
    }
    return true
}

It's not that pretty as extension but work as charm :)

查看更多
祖国的老花朵
6楼-- · 2019-01-09 03:01

You can use the as? operator, which returns an optional value (nil if the downcast fails)

if let latestValue = sensor["latestValue"] as? String {
    cell.detailTextLabel.text = latestValue
}

I tested this example in a swift application

let x: AnyObject = NSNull()
if let y = x as? String {
    println("I should never be printed: \(y)")
} else {
    println("Yay")
}

and it correctly prints "Yay", whereas

let x: AnyObject = "hello!"
if let y = x as? String {
    println(y)
} else {
    println("I should never be printed")
}

prints "hello!" as expected.

查看更多
一夜七次
7楼-- · 2019-01-09 03:01

You could also use is to check for the presence of a null:

if sensor["latestValue"] is NSNull {
    // do something with null JSON value here
}
查看更多
登录 后发表回答