Reputation: 4519
When I call the function CacheStation I get the error: CoreData: error: Failed to call designated initializer on NSManagedObject class SaveModel. Nothing more nothing less. How can I resolve this issue?
SaveModel.swift:
import Foundation
import CoreData
import UIKit
class SaveModel: NSManagedObject {
func CacheStations(){
// create an instance of our managedObjectContext
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// we set up our entity by selecting the entity and context that we're targeting
let entity = NSEntityDescription.insertNewObjectForEntityForName("CachedStations", inManagedObjectContext: moc) as! SaveModel
//add the data
entity.land = "nl";
// we save our entity
do {
try moc.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
SaveModel+CoreDataProperties.swift:
import Foundation
import CoreData
extension SaveModel {
@NSManaged var land: String?
}
Where I call CacheStations:
import UIKit
class ViewController: UIViewController {
@IBAction func saveShizzle(sender: AnyObject) {
let sm = SaveModel();
sm.CacheStations();
}
}
Upvotes: 2
Views: 1193
Reputation: 21536
This line:
let sm = SaveModel();
uses the standard init()
method to create an instance of SaveModel
, but NSManagedObjects
must be initialised using the designated initialiser:
init(entity entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)
(or, as in your CacheStations method, using NSEntityDescription.insertNewObjectForEntityForName(_, inManagedObjectContext: moc)
which calls the designated initialiser).
Since it seems sm
is created only to have an instance on which to call CacheStations
, I would change that method to a class method:
class func CacheStations(){
and change your saveShizzle
method to use the class method:
@IBAction func saveShizzle(sender: AnyObject) {
SaveModel.CacheStations();
}
Upvotes: 2
Reputation: 70936
Here's what happens:
let sm = SaveModel();
you are creating a new instance of SaveModel
.SaveModel
is a subclass of NSManagedObject
NSManagedObject
has a designated initializer called init(_: insertIntoManagedObjectContext:)
You need to either call the NSManagedObject
designated initializer or create your own designated initializer that calls the superclass designated initializer.
Upvotes: 0