我正在编写一个库,允许开发人员像这样在 coreData 上应用 SQL 代码:
let manager = coreSQL()
manager.prepare("INSERT INTO Entity (name, age) VALUES (?,?)")
manager.execute(["Chuck Norris" , "76"])
我用这个插入 coreData
let context:NSManagedObjectContext = appDel.managedObjectContext
let newRow = NSEntityDescription.insertNewObjectForEntityForName(tableName, inManagedObjectContext: context)
if (columnsArray.count == values.count){
for i in 0 ..< columnsArray.count{
newRow.setValue(values[i], forKey: columnsArray[i])
}
do {try context.save()} catch _ {}
}
columnsArray = ["name", "age"]
values = ["Chuck Norris", "76"]
问题是在我的 coreData 对象中,age 属性是 Integer 类型,您可能会注意到 Chuck Norris 的 age 是 String,所以当我尝试执行我的应用程序时,出现错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“ Not Acceptable 属性值类型:property =“age”;所需类型 = NSNumber;给定类型 = _TtCs19_NSContiguousString;值 = 76。'
问题是:如何识别属性类型以便将值转换为相同类型
最佳答案
您可以通过询问实体来识别属性类型:
let context:NSManagedObjectContext = appDel.managedObjectContext
let newRow = NSEntityDescription.insertNewObjectForEntityForName(tableName, inManagedObjectContext: context)
let attributes = newRow.entity().attributesByName()
if (columnsArray.count == values.count){
for i in 0 ..< columnsArray.count{
let attributeDescription = newRow.entity.attributesByName[columnsArray[1]]
switch attributeDescription.attributeType {
case StringAttributeType:
}
newRow.setValue(values[i], forKey: columnsArray[i])
}
try! context.save()
}
关于ios - 识别核心数据属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531054/