Reputation: 1222
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
Upvotes: 0
Views: 289
Reputation: 46718
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()
}
Upvotes: 2