Reputation: 281
I'm little bit confused with initWithEntity:insertIntoManagedObjectContext:
.
According to Swift documentation(Two-Phase Initialization) I should call super.init
after I initialise all new properties of subclass.
But when I do so with following code I get error:
//In subclass of NSManagedObject
init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?, origin: NavCoordinate, destination:NavCoordinate, city: String, averageSpeedKmPH:NSNumber, client:String)
{
self.origin = origin
self.destination = destination
self.city = city
self.averageSpeedKmPH = averageSpeedKmPH
self.client = client
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
The problem is I get error: "Super.init called multiple times in initializer"
If I call super.init...
first than it is ok.
Also documentation for initWithEntity:insertIntoManagedObjectContext says:
If you override initWithEntity:insertIntoManagedObjectContext:, you must ensure that you set self to the return value from invocation of super’s implementation, as shown in the following example:
But without any example.
What is the correct way to override initWithEntity:insertIntoManagedObjectContext:
?
Upvotes: 0
Views: 814
Reputation: 281
I decided to solve to with calling insertNewObjectForEntityForName
first and then call setup
on entity. This seems to be best solution because this way you don't break Swift Two-Phase Initialization and support core data undo, redo.
let journey = NSEntityDescription.insertNewObjectForEntityForName("JourneyEntity", inManagedObjectContext: moc) as! Journey
journey.setupJourney(origin, destination: destination, city: city, averageSpeedKmPH: self.user.averageSpeedKmPH, client:client)
Upvotes: -1
Reputation: 15589
The documentation of init(entity entity: NSEntityDescription,
insertIntoManagedObjectContext context: NSManagedObjectContext?)
says
You are discouraged from overriding this method—you should instead override awakeFromInsert and/or awakeFromFetch (if there is logic common to these methods, it should be factored into a third method which is invoked from both). If you do perform custom initialization in this method, you may cause problems with undo and redo operations.
The correct way is to override awakeFromInsert instead of init.
Upvotes: 2