2015-02-10 85 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"); 
    } 
} 

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