【问题标题】:[NSNull length]: unrecognized selector sent to instance 0x10f8c6fc0' swift 4 iOS[NSNull 长度]:无法识别的选择器发送到实例 0x10f8c6fc0' swift 4 iOS
【发布时间】:2018-10-17 08:19:53
【问题描述】:

我是这样从模型中获取数据的

if let birthdate = personInfo?.str_Birthdate {
    cell.dobTF.text = birthdate
}

但应用程序崩溃并返回此错误

'-[NSNull 长度]:无法识别的选择器发送到实例 0x10f8c6fc0'

【问题讨论】:

  • 看起来str_BirthdateNSNull,而不是字符串实例。价值从何而来?
  • 请说明str_Birthdate的价值从何而来
  • 基本上str_Birthdate有nsnull值但不知道怎么处理
  • @EneaDume 它是客观的 c 模型 nsstring 属性。我这没有价值,但问题是如何在其上添加对 nsnull 值的检查。
  • 如果让birthdate = personInfo?.str_Birthdate 就崩溃

标签: ios swift4 xcode10


【解决方案1】:

你在这里得到的是NSNull。它是在 Objective-C 数组和字典的上下文中表示 null 的对象。特别是在 JSON 中,它区分接收字段 (null) 而不是根本不接收字段。在你的情况下,我假设这个值被强制解包为一个字符串,所以错误有点晚了。请尝试以下方法:

if let dateObject = personInfo?.str_Birthdate {
    if let nullObject = dateObject as? NSNull {
        // A field was returned but is (null)
    } else if let stringObject = dateObject as? String {
        cell.dobTF.text = stringObject
    } else {
        // Unknown object
    }
} else {
    // This field is missing
}

您实际上可以将所有 NSNull 实例转换为 nil 使用类似的东西:

func removeNSNullInstancesFrom(_ item: Any?) -> Any? {
    guard let item = item else { return nil }
    if let _ = item as? NSNull {
        return nil
    } else if let array = item as? [Any] {
        return array.compactMap { removeNSNullInstancesFrom($0) }
    } else if let dictionary = item as? [String: Any] {
        var newDict: [String: Any] = [String: Any]()
        dictionary.forEach { item in
            guard let value = removeNSNullInstancesFrom(item.value) else { return }
            newDict[item.key] = value
        }
        return newDict
    } else {
        return item
    }
}

您可以在整个响应对象或特定项目上使用它。在您的情况下,您可以这样做:cell.dobTF.text = removeNSNullInstancesFrom(birthdate)

但此方法通常应从 JSON 标准的字段、数组和字典中递归删除所有 NSNull 实例。

【讨论】:

  • 类型推断导致不良行为的一个很好的例子。
猜你喜欢
  • 1970-01-01
  • 2015-12-24
  • 1970-01-01
  • 2023-04-09
  • 2023-03-11
  • 1970-01-01
  • 2011-08-23
  • 2023-03-09
  • 2021-12-29
相关资源
最近更新 更多