0

I want to use today extension to add some data to coreData but I get some problems :

"CoreData: error: Failed to call designated initializer on NSManagedObject class"

and

"sharedpplication()' is unavailable use view controller based solutions where appropriate instead"

I'm using this class in viewController and Today Extension :

let chestModel=Chest()

This is my Class code :

class Chest: NSManagedObject {
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let request = NSFetchRequest(entityName: "Chest")

func newChest(no:String,type:String){
    let chest = NSEntityDescription.insertNewObjectForEntityForName("Chest", inManagedObjectContext: self.moc) as! Chest
    chest.no=no
    chest.type=type
    do{
        try self.moc.save()
    }catch{
        fatalError("Save failed")
    }
}

func chestCount()-> Int{
    do{
        let results = try moc.executeFetchRequest(request) as! [Chest]
        return results.count
    }catch{
        fatalError("GetCount Failed!!")
    }
}

}

How can I solve this problem and make today extension save/load coreData?

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
  • An extension is not based on `UIApplication`. Use a singleton for both application and extension or copy the Core Data stack code in the extension. You cannot use the default initializer `()` on `NSManagedObject`. Core Data management is useless without the managed object context reference. You have to use the designated initializer passing the `moc` reference. – vadian Apr 01 '16 at 09:54
  • Thanks,I'll try it – Winston Chuang Apr 02 '16 at 07:06

0 Answers0