当我运行下面的代码行时,获取错误消息'无法将Swift.Int16类型的值转换为Swift.AnyObject'。错误发生在该行:
'newWorkout.setValue(totalTimeConverted as!AnyObject,forKey:“workoutTime”)'
锻炼是我的实体的名称。它有两个属性;
NSDate类型的workoutDate
Int16类型的workoutTime。
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let newWorkout = NSEntityDescription.insertNewObjectForEntityForName("Workout", inManagedObjectContext: context) as! Workout
let totalTimeConverted = Int16(totalTime)
// Add parameters
newWorkout.setValue(totalTimeConverted as! AnyObject, forKey: "workoutTime")
newWorkout.setValue(NSDate(), forKey: "workoutDate")
do {
try context.save()
} catch {
print("Error saving data")
}
do {
let request = NSFetchRequest(entityName: "Workout")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject]{
let time = item.valueForKey("workoutTime")
let workoutDate = item.valueForKey("workoutDate")
print(time!, workoutDate!)
}
}
} catch{
print("Error loading data")
}
答案 0 :(得分:0)
那是因为Int16
是原始的,而不是对象,只是不能被转换为" AnyObject"。
如Dalija Prasnikar's answer所述,您可以将您的号码包装到NSNumber对象中。
答案 1 :(得分:0)
您无法将Int16
投射到AnyObject
。它是值类型而不是类。
您可以使用NSInteger
进行正确的类型转换
newWorkout.setValue(NSInteger(totalTimeConverted), forKey: "workoutTime")