我一直在努力创建一个管理Core Data的类。 我似乎无法通过“无法在NSManaged对象上调用指定的初始化程序”
我该如何解决这个问题?
这是我创建的用于管理数据的类:
import Foundation
import CoreData
import UIKit
class Hours: NSManagedObject {
@NSManaged var date: NSDate
@NSManaged var startTime: NSDate
@NSManaged var endTime: NSDate
@NSManaged var totalTime: Double
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?){
let entity = NSEntityDescription.entityForName("Hours", inManagedObjectContext: context!)
super.init(entity: entity!, insertIntoManagedObjectContext: context)
}
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context:NSManagedObjectContext {
get{
return appDel.managedObjectContext
}
}
class func insertTimes(date: NSDate, startTime:NSDate, endTime:NSDate,totalTime:Double) -> Hours{
let hour:Hours = Hours()
let newDate:Hours = NSEntityDescription.insertNewObjectForEntityForName("Hours", inManagedObjectContext: hour.context) as! Hours
print("date = \(date), start = \(startTime), end = \(endTime), total = \(totalTime)")
newDate.date = date
newDate.startTime = startTime
newDate.endTime = endTime
newDate.totalTime = totalTime
/*
newDate.setValue(date, forKey: "date")
newDate.setValue(startTime, forKey: "startTime")
newDate.setValue(endTime, forKey:"endTime")
newDate.setValue(totalTime, forKey: "totalTime")
*/
do{
try hour.context.save()
print("Succesfully saved")
}catch{
print("Unresolved save error")
}
return newDate
}
func returnDate(){
//Does not work YET
let request = NSFetchRequest(entityName: "Hours")
//request.returnsObjectsAsFaults = false
do{
let results = try context.executeFetchRequest(request)
print(results)
}catch{
print("Unresolved fetch error")
}
}
}
在按下按钮后,我尝试使用以下代码行调用方法insertTimes
。
@IBAction func saveData(sender: AnyObject) {
let inserted:Hours = Hours.insertTimes(date, startTime: startEndDate.startTime, endTime: startEndDate.endTime, totalTime: timeInterval)
}
请注意我的所有变量都是正确的类型。
来源可以在https://github.com/bbriann123/PayDay/blob/master/Hours.swift
找到答案 0 :(得分:0)
看看这些:
在AppDelegate
中使用" Loon Calculator"而不是" DayDataModel":https://github.com/bbriann123/PayDay/blob/master/Loon%20Calculator/AppDelegate.swift#L55(数据模型文件名显然是" DayDataModel":https://github.com/bbriann123/PayDay/tree/master/Loon%20Calculator/DayDataModel.xcdatamodeld/DayDataModel.xcdatamodel)
在数据模型中,您没有指定"小时"作为"小时"的定制类实体(查看核心数据检查器)
此外,您到达NSManagedObjectContext
:https://github.com/bbriann123/PayDay/blob/master/Hours.swift#L25-L30
也许你需要一本更好的核心数据书(或者你用来学习的任何东西)?