方法 load() 定义了 Objective-C class 方法 'load',这是 Swift 1.2 不允许的

Method load() defines Objective-C class method 'load', which is not permitted by Swift 1.2

我正在使用 Parse,我正在创建一个符合 PFSubclassing 协议的 PFObject subclass! 一切正常,但现在我正在使用 Swift 1.2,它给了我这个错误:

1. override class func load() {
2.      self.registerSubclass()
3. }

第 1 行:方法 'load()' 定义了 Objective-C class 方法 'load',Swift 1.2

不允许这样做

有人遇到过这个问题吗?我该如何解决?

我将其替换为:

override class func initialize() {
}

我在 Parse.setApplicationId 之前为 PFObject 的每个子类调用 AppDelegate 中的 registerSubclass() 方法并且它有效。

覆盖 load() 从未 与 Swift 一起工作。早些时候,它根本就没有被调用。当时我为 Apple 提交了一个错误(错误 ID 18423731),最近我收到回复说这个问题已经通过明确通知开发人员在 Swift.

中不允许这样做来解决。
extension UIButton {
    // !! never called
    override public class func load() { // Method 'load()' defines Objective-C class method 'load', which is not permitted by Swift 1.2
        super.load()
        println("not called earlier anyway");
    }
}

所以……不要。即使文档另有说明。

有一篇关于方法调配的 NSHispster 文章在不同的上下文中涉及到这一点:

Unfortunately, a load class method implemented in Swift is never called by the runtime, rendering that recommendation an impossibility. Instead, we're left to pick among second-choice options:

  • Implement method swizzling in initialize. This can be done safely, so long as you check the type at execution time and wrap the swizzling in dispatch_once (which you should be doing anyway).

  • Implement method swizzling in the app delegate. Instead of adding method swizzling via a class extension, simply add a method to the app delegate to be executed when application(_:didFinishLaunchingWithOptions:) is called. Depending on the classes you're modifying, this may be sufficient and should guarantee your code is executed every time.

Link: http://nshipster.com/swift-objc-runtime/

-

来自开发论坛的更多信息:

Swift 1.1 allowed you to define "+load" methods with "class func load()", but they were not actually run at startup time of your app like Objective-C +load methods are. Swift 1.2 bans them to avoid the impression that this might work.

Link: https://devforums.apple.com/message/1102025#1102025

-

tl;dr initialize()didFinishLaunchingWithOptions 似乎是 Swift.

中适合此类事情的地方

试试这个:

override class func initialize() {
   var onceToken : dispatch_once_t = 0;
   dispatch_once(&onceToken) {
      self.registerSubclass()
   }
}

Parse 文档已更新:https://www.parse.com/docs/ios/guide#objects-subclassing-pfobject