【问题标题】:Getting NSNumber exception while converting data based on attribute type根据属性类型转换数据时获取 NSNumber 异常
【发布时间】:2017-03-07 20:44:17
【问题描述】:

使用此处显示的模式:identify coreData Attribute's type

// setting up entity and attributes list
let entity: NSManagedObject = NSEntityDescription.insertNewObject(forEntityName: entityName, into: backgroundContext)

let entityAttributes = entity.entity.attributesByName

...

// looping through provided property names and values
let propertyType: NSAttributeType = entityAttributes[propertyName]!.attributeType

switch propertyType {

// StringAttributeType, used in link example, isn't available in Swift 3, Xcode 8.0
//case StringAttributeType:

// using instead: NSAttributeType constants                 
case .stringAttributeType:
    let propertyValue: String = propertyValues[idx]
    entity.setValue(propertyValue, forKey: propertyName)

case .integer16AttributeType:
    let propertyValue = Int16(propertyValues[idx])
    entity.setValue(propertyValue, forKey: propertyName)

...

但是,获得 Int16 值的异常:

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'不可接受的属性值类型:property = "this_prop_name";所需类型 = NSNumber;给定类型 = _SwiftValue;值 = 3。'

我认为我们不再需要使用 Swift 在 CoreData 中进行 NSNumber 转换。或者,我是否正在经历低脑缺氧时刻?

通过实体的属性类型转换 Int16(或任何其他数值)的正确 Swift 3 方法是什么?

【问题讨论】:

  • 我建议使用NSManagedObject 子类。 Swift 3 让处理变得更加容易。
  • 我不确定我是否看到你真正想要实现的目标,但 Swift 不会将 Int16 映射到 NSNumber(这将随着 Swift 3.1 改变)。通过setValue:forKey: 设置整数属性需要IntNSNumber 参数。
  • @MartinR,我正在从文件中读取数据。实体的属性具有混合类型(大多数是字符串,有些是整数,有些是双精度型),但文件读取的结果是所有字符串值。因此,我需要将这些 String 值转换为其关联实体属性所需的适当类型。 vadian:我正在使用 NSManagedObject 子类。
  • 对整数属性尝试let propertyValue = Int(propertyValues[idx])
  • 成功了,@MartinR!输入它作为答案,我会接受。

标签: ios swift core-data swift3 xcode8


【解决方案1】:

通过键值编码设置核心数据属性需要值 这是NSObject 子类的实例,例如NSStringNSNumber.

在 Swift 3.0 之前,只有某些标量类型可以桥接到 NSNumber 并返回,例如IntUIntDoubleFloat,但不是固定大小 类型如Int16。 (这将在未来的 Swift 版本中改变,比较 SE-0139 Bridge Numeric Types to NSNumber and Cocoa Structs to NSValue.)

因此在

entity.setValue(propertyValue, forKey: propertyName)

propertyValue 必须是 IntNSNumber。在你的情况下 对于“整数 16”属性,Int 将大到足以容纳 所有可能的值:

let propertyValue = Int(propertyValues[idx])

【讨论】:

    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2023-04-09
    • 2021-03-18
    • 2014-10-29
    相关资源
    最近更新 更多