【发布时间】: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:设置整数属性需要Int或NSNumber参数。 -
@MartinR,我正在从文件中读取数据。实体的属性具有混合类型(大多数是字符串,有些是整数,有些是双精度型),但文件读取的结果是所有字符串值。因此,我需要将这些 String 值转换为其关联实体属性所需的适当类型。 vadian:我正在使用 NSManagedObject 子类。
-
对整数属性尝试
let propertyValue = Int(propertyValues[idx])。 -
成功了,@MartinR!输入它作为答案,我会接受。
标签: ios swift core-data swift3 xcode8