当我尝试将NSDate
添加到newWorkout时;代码行:
newWorkout.setValue(currentTime, forKey: "workoutDate")
即使我在执行代码行之前打印currentTime,它也返回nil,返回正确的NSDate
。保存中的核心数据是名为Workout的实体,其中两个属性为Int16
类型的workoutTime和类型为Date的workoutDate。
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)
let currentTime = NSDate()
print(currentTime)
// Add parameters
newWorkout.setValue(NSInteger(totalTimeConverted), forKey: "workoutTime")
newWorkout.setValue(currentTime, 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")
print(time)
let workoutDate = item.valueForKey("workoutDate")
print(workoutDate)
print(time!, workoutDate!)
}
}
} catch{
print("Error loading data")
}