swift 1.2 覆盖 NSManagedObject 扩展中的 prepareForDeletion

swift 1.2 override prepareForDeletion in NSManagedObject extension

覆盖函数 prepareForDeletion 在 swift 1.2

中失败
// Playground - noun: a place where people can play

import UIKit
import CoreData

extension NSManagedObject {
    @objc func prepareForDeletion() {
        println("deleting object")
    }
}

Error: method 'prepareForDeletion()' with Objective-C selector 'prepareForDeletion' conflicts with previous declaration with the same Objective-C selector

@objc func prepareForDeletion() {
           ^

CoreData.NSManagedObject:31:14: note: 'prepareForDeletion' previously declared here

@objc func prepareForDeletion()

有人知道吗?

谢谢 罗恩

不能在相同class的扩展中覆盖class中的方法,这样做总是未定义的行为。

为了重写 Swift 中的 Objective-C 方法,这在 Xcode 6.2 现在可以在 Xcode 6.3 beta 中正确诊断。

注意Objective-C中对应的做法—— 在相同 class 的 Objective-C 扩展中覆盖方法 – 也是不允许的,见 "Avoid Category Method Name Clashes":

If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. This is less likely to be an issue if you’re using categories with your own classes, but can cause problems when using categories to add methods to standard Cocoa or Cocoa Touch classes.

您可以做的是重写自定义中的方法 NSManagedObject subclasses.