I've liked Martin's solution for a long time, but I recently ran into trouble with it. If the object has been KVO observed, then this will crash. Self
in that case is the KVO subclass, and the result of objectWithID
is not that subclass, so you'll get a crash like "Could not cast value of type 'myapp.Thing' (0xdeadbeef) to 'myapp.Thing' (0xfdfdfdfd)." There are two classes that call themselves myapp.Thing
, and as!
uses the actual class object. So Swift is not fooled by the noble lies of KVO classes.
The solution is to replace Self
with a static type parameter by moving this to the context:
extension NSManagedObjectContext {
func transferredObject<T: NSManagedObject>(object: T) -> T {
return objectWithID(object.objectID) as! T
}
}
T
is purely defined at compile-time, so this works even if object
is secretly a subclass of T
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…