识别coreData属性的类型 [英] identify coreData Attribute's type
问题描述
我正在编写一个库,该库允许开发人员将SQL代码应用于coreData,如下所示:
Im writing a library that allows developers to apply SQL code on coreData like so:
let manager = coreSQL()
manager.prepare("INSERT INTO Entity (name, age) VALUES (?,?)")
manager.execute(["Chuck Norris" , "76"])
要插入coreData中,我要使用此
to insert in coreData i use this
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 = [名称",年龄"]
值= [查克·诺里斯"(Chuck Norris),"76"]
问题在于,在我的coreData对象中,age Attribute的类型为Integer,并且您可能会注意到Chuck Norris的age为String,因此当我尝试执行我的应用程序时会收到错误消息:
the problem is that in my coreData object the age Attribute is of type Integer and as you may noticed Chuck Norris's age is String so when i try to execute my application i get an error :
由于未捕获的异常"NSInvalidArgumentException"而终止应用程序,原因:属性的值的类型不可接受:property ="age";所需的类型= NSNumber;给定类型= _TtCs19_NSContiguousString;值= 76.'
问题是:如何识别属性类型以将值转换为相同类型
The question is: how can i identify the attribute type in order to cast the value to the same type
推荐答案
您可以通过询问实体来标识属性类型:
You can identify the attribute type by asking the entity:
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() }
这篇关于识别coreData属性的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!