When an instance of my class is initialized using NSCoding
, I want to replace it with an existing object in the Core Data database instead of calling:
super.init(entity: ..., insertIntoManagedObjectContext: ...)
as that would insert a new object into the database.
class MyClass: NSManagedObject, NSCoding {
required init(coder aDecoder: NSCoder) {
// Find a preexisting object in the Core Data database
var ctx = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var fs = NSFetchRequest(entityName: "MyClass")
// ... Configure the fetch request based on values in the decoder
var err: NSErrorPointer = nil
var results = ctx.executeFetchRequest(fs, error: err)
// ... Error handling, etc
newObject = results[0] as! MyClass
// Attempt to replace self with the new object
self = newObject // ERROR: "Cannot assign to 'self' in a method"
}
func encodeWithCoder(aCoder: NSCoder) {
// Encode some identifying property for this object
}
}
This was a fairly common Objective-C pattern, but I can't figure out how to replicate this in Swift 1.2, since assigning another object to self
yields a compile error:
Cannot assign to 'self' in a method
and even if it did succeed, it seems Swift requires that I call NSManagedObject
's designated initializer which would insert a new object into the database.
How do I replace an object with a pre-existing one in the database at initialization time? And if its not possible (please provide a reference if this is the case), what pattern should I be using instead?