0
votes

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"])

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 = ["name", "age"]

  • values = ["Chuck Norris" , "76"]

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 :

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "age"; desired type = NSNumber; given type = _TtCs19_NSContiguousString; value = 76.'

The question is: how can i identify the attribute type in order to cast the value to the same type

1
thanks that partially solved my problem but i just noticed that by setting the values array to [AnyObject] instead of [String] solved my problem without adding more codeMed Abida
If you are doing to leave the catch blank like that, just do a try! instead. Otherwise you are hiding errors and your library is going to be a nightmare to debug.Marcus S. Zarra

1 Answers

2
votes

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