0

我正在使用 Swift 5。

为什么会在什么NSInvalidArgumentException时候发生responseValues["CustomerID"] == '<null>'

显然,这if responseValues["CustomerID"] is NSNull不是诀窍。应进行哪些检查以避免NSInvalidArgumentException

self.api.getCustomerId(callback: { getIDResult in
  if let responseValues = getIDResult["ResponseValues"] {

    print("GET CUSTOMER ID RESULT")
    print(responseValues)

    if responseValues["CustomerID"] is NSNull { // <---- crashes here when null
        print("CustomerID is null")
    }
    else{
        print("CustomerID is NOT null")
    }
  }
})

成功的结果

GET CUSTOMER ID RESULT
{
    CustomerID = 403254;
}
CustomerID is NOT null

遇到空客户 ID 时的崩溃结果

GET CUSTOMER ID RESULT
{
    CustomerID = "<null>";
}

崩溃与以下

019-11-21 12:13:16.819033-0500 MyApp[29412:4207932] -[NSNull _fastCStringContents:]: unrecognized selector sent to instance 0x7fff80615710
2019-11-21 12:13:16.820557-0500 MyApp[29412:4207932] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull _fastCStringContents:]: unrecognized selector sent to instance 0x7fff80615710'

有人质疑该值是否实际上为 null,这是该字典的一些调试信息:

在此处输入图像描述

4

1 回答 1

0

如果 responseValues 是一个字典,你可以这样做

if let customerId = responseValues["CustomerID"] as? String
{
   print(customerId)
}
else
{
   print("customer id isn't available")
}

如果您想知道是否为空,则必须更改为 Codable

于 2019-11-21T17:33:48.657 回答