2015-02-10 58 views
24

我正在使用Parse,並且我正在創建一個符合協議PFSubclassing的PFObject子類! 這是工作一切正常,但現在,我使用雨燕1.2,這讓我這個錯誤:方法load()定義Objective-C類的方法'load',這是不允許的Swift 1.2

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

線1:方法「的load()」定義的Objective-C類的方法「負荷」,這是不允許的斯威夫特1.2

任何人都有這個問題呢?我該如何解決?

+0

你的意思是說'function',而不是'func'?這是一種解析的東西嗎? – matt 2015-02-10 02:55:55

回答

15

有關於方法混寫的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.

鏈接: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.

鏈接:https://devforums.apple.com/message/1102025#1102025

-

TL;博士initialize()didFinishLaunchingWithOptions似乎是在斯威夫特這樣的事情像樣的地方。

+0

最完整的答案,所以我標記爲正式答案!謝啦! – txaidw 2015-02-11 10:47:23

5

我得到它的工作與替換它:

override class func initialize() { 
} 
+4

請注意'+ load'和'+ initialize'是不同的。加載二進制文件時,「+ load」運行,不管該類是否被使用;你可以有多個'+ load'方法 - 除了主類之外,每個類都有一個 - 所有這些方法都不會相互干擾(通常類別方法用相同名稱替代現有的方法)。另一方面,'初始化',當班級第一次被髮送消息時,延遲運行。 – newacct 2015-02-10 02:58:55

+0

@newacct你知道相當於load()在Swift中嗎?現在我要離開上面的評論作爲答案,因爲它現在解決我的問題 – txaidw 2015-02-10 03:06:59

6

我打電話Parse.setApplicationId之前在AppDelegate中registerSubclass()方法的PFObject每個子類中,它的作品。

4

覆蓋load()從來沒有與斯威夫特合作。更好的是它根本不叫。當時我爲蘋果公司提交了一個bug(Bug 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"); 
    } 
} 

所以....不要。即使文檔另有說明。