How to use generic types to get object with same type

前端 未结 3 1751
南笙
南笙 2020-12-06 13:24

I have extension for NSManagedObject that should help me to transfer objects between contexts:

extension NSManagedObject {

    func transferTo(         


        
3条回答
  •  眼角桃花
    2020-12-06 14:01

    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(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.

提交回复
热议问题