gpt4 book ai didi

ios - 根据属性类型转换数据时出现 NSNumber 异常

转载 作者:可可西里 更新时间:2023-11-01 01:28:10 24 4
gpt4 key购买 nike

使用此处显示的模式: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 值的异常:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "this_prop_name"; desired type = NSNumber; given type = _SwiftValue; value = 3.'

我认为我们不再需要使用 Swift 在 CoreData 中进行 NSNumber 转换。或者,我是不是脑缺氧了?

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

最佳答案

通过键值编码设置核心数据属性需要值它们是 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。在你的情况下“Integer 16”属性的 Int 足够大以容纳所有可能的值:

let propertyValue = Int(propertyValues[idx])

关于ios - 根据属性类型转换数据时出现 NSNumber 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40246088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com