1

次のコードがあります

protocol JsonParseDescriptor {
 //some required methods
   func parsePrimitives() {
}

extension JsonParseDescriptor where Self: NSManagedObject {
   func parsePrimitives() {
      self.setValue(1, forKey: "id") //this throws an error in swift stating Ambiguous use of setValueForKey
      self.setValue(1, forKey: "id") //this does not throw any compile-time error
   }

}

setValue:ForKey: がこのエラーを引き起こしている理由はありますか? 興味深いことに、setValue:ForKeyPath: はこの問題の原因ではありません。副作用が発生し、setValue:ForKey 以外で機能する場合に備えて、後者を使用することを恐れています。アイデアはありますか?

4

1 に答える 1

0

これは、バグの原因となった私のコードでした。

func create<U : NSManagedObject>(entityName : String, primaryKey : String, value : AnyObject) -> U {
    let created : U = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: providedContext) as! U
    created.setValue(value, forKey: primaryKey)
    return created
}

これは、それを作成しないコードです:

func create<U : NSManagedObject>(entityName : String, primaryKey : String, value : AnyObject) -> U {
    let created = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: providedContext)
    created.setValue(value, forKey: primaryKey)
    return created as! U
}

私の推測では、コンパイラ (または静的アナライザー) は、動的ディスパッチをどこにルーティングする必要があるかを判断できません。または多分それはただのバグです。

いずれにせよ、この回避策が役立つことを願っています。

于 2016-05-09T22:41:57.767 に答える