ios - 识别核心数据属性类型

标签 ios swift core-data swift2

我正在编写一个库,允许开发人员像这样在 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/

相关文章:

ios - 后台线程中的核心数据锁

iphone - 从 iOS 设备到 Web 服务的签名请求

iphone - 删除警告错误(丢失的文件夹不再存在)

ios - 如何在 API .js 上连接我的 iOS 应用程序

swift - 如何从自定义 SKAction Swift 中引用节点

ios - Swift 函数/方法中的 "_"字符

ios - CoreData - 对 ManagedObjectContext 使用 AppDelegate、单例或 View Controller 上的属性?

ios - 从 UITabBarController 场景转到 ViewController 并返回 "hides"UITabBar

ios - 如何在 AVCapture 设备输入上禁用摄像头麦克风

iphone - iOS 5 核心数据卡住