ios 检测 NSDictionary 中的 Null 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24026609/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:21:11  来源:igfitidea点击:

Detect a Null value in NSDictionary

iosswiftnsnull

提问by Jeff

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

我有一个NSDictionary从 API 服务器的 JSON 响应填充的。有时,此字典中键的值是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 NSStringI get a crash, which I thinkis because I'm trying to coerce Nullinto a string.

问题是,当我尝试将值强制转换为一个时,NSString我会崩溃,我认为这是因为我试图将其强制Null转换为字符串。

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.

如果我只需要将所有这些都包装在一个条件中,那很好。我只是无法弄清楚那个条件是什么。回到 Objective-C 世界,我会与之比较,[NSNull null]但这似乎不适用于 Swift。

回答by Gabriele Petronella

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

您可以使用as?运算符,它返回一个可选值(nil如果向下转换失败)

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

I tested this example in a swift application

我在一个 swift 应用程序中测试了这个例子

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

它正确打印"Yay",而

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

prints "hello!"as expected.

"hello!"按预期打印。

回答by iraxef

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

您还可以使用is检查是否存在空值:

if sensor["latestValue"] is NSNull {
    // do something with null JSON value here
}

回答by B?a?ej

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

我正在使用这些组合。此外,该组合检查 object 是否不是"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 :)

它不像扩展那么漂亮,但很有魅力:)

回答by matt

NSNull is a class like any other. Thus you can use isor asto test an AnyObject reference against it.

NSNull 是一个和其他类一样的类。因此,您可以使用isas针对它测试 AnyObject 引用。

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:

因此,在我的一个应用程序中,我有一个 NSArray,其中每个条目都是 Card 或 NSNull(因为您不能将 nil 放在 NSArray 中)。我将 NSArray 作为数组获取并循环遍历它,切换我得到的对象类型:

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.

这与您的场景不同,但它来自转换为 Swift 的工作应用程序,并说明了完整的通用技术。

回答by André Slotta

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

到目前为止,测试看起来不错

回答by loopmasta

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

我有一个非常相似的问题,并通过转换为原始 NSDictionary 值的正确类型来解决它。如果您的服务返回这样的混合类型 JSON 对象

{"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

这确实解决了我的问题。在 swift 关闭中查看BAD_INSTRUCTION