【问题标题】:identify coreData Attribute's type识别核心数据属性类型
【发布时间】:2016-04-10 14:33:01
【问题描述】:

我正在编写一个库,允许开发人员在 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 的年龄是 String,所以当我尝试执行我的应用程序时出现错误:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“属性值的不可接受类型:property = “age”;所需类型 = NSNumber;给定类型 = _TtCs19_NSContiguousString;值 = 76。'

问题是:如何识别属性类型以便将值转换为相同的类型

【问题讨论】:

  • 感谢这部分解决了我的问题,但我只是注意到通过将值数组设置为 [AnyObject] 而不是 [String] 解决了我的问题而无需添加更多代码
  • 如果您要像这样将 catch 留空,请改为使用 try!。否则,您将隐藏错误,并且您的库将成为调试的噩梦。

标签: ios swift core-data swift2


【解决方案1】:

您可以通过询问实体来识别属性类型:

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()
}    

【讨论】:

  • 我们已经找到了 2 个解决方案!但是由于我测试了你的代码并且它有效,我检查了你的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
相关资源
最近更新 更多