加载指定的初始化核心数据失败

时间:2015-09-27 18:56:43

标签: ios swift core-data

我一直在努力创建一个管理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

找到

1 个答案:

答案 0 :(得分:0)

看看这些:

也许你需要一本更好的核心数据书(或者你用来学习的任何东西)?