2017-09-22 60 views
3

Swiftling在斯威夫特4不再有效。方法在swift 4迅速4

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

这是我已经找到了解决方案,所以想离开的问题和回答别人。

回答

3

初始化()不再暴露:Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift

所以这样做,现在是通过公共静态方法来运行你的调酒代码。

例如

在扩展名: (此扩展用于在动工开放源码:https://github.com/kickstarter/ios-oss/blob/master/Library/DataSource/UIView-Extensions.swift

private var hasSwizzled = false 

extension UIView { 
    final public class func doBadSwizzleStuff() { 
     guard !hasSwizzled else { return } 

     hasSwizzled = true 
     swizzle(self) /* This is pseudo - run your method here */ 
    } 
} 

在应用程序委托: (此方法是在动工打开用于源代码:https://github.com/kickstarter/ios-oss/blob/7c827770813e25cc7f79a28fa151cd713efe936f/Kickstarter-iOS/AppDelegate.swift#L33

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any]?) -> Bool 
{ 
    UIView.doBadSwizzleStuff() 
} 

另一种方法是使用一个单例:如果你有机会到AppDelegate的源代码

extension UIView { 
    static let shared : UIViewController = { 
     $0.initialize() 
     return $0 
    }(UIViewController()) 

    func initialize() { 
     // make sure this isn't a subclass 
     guard self === UIViewController.self else { return } 

     let swizzleClosure:() = { 
      UIViewController().swizzle() /* This is pseudo - run your method here */ 
     }() 
     swizzleClosure 
    } 
} 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any]?) -> Bool 
{ 
    _ = UIViewController.shared 
} 
+0

这仅适用。我正在编写一个库,并希望利用Swizzling在ViewController的“viewDidLoad”块中运行特定的方法。我试图让我的库尽可能容易地让客户实现,虽然我可以让他们向AppDelegate添加代码,但如果可能的话,我宁愿使用Swizzling(如果需要,可以选择禁用它)。任何关于这个获得“AppDelegate-free”Swift在Swift 4.0中工作的想法?谢谢! Craig – CPR

+1

我看到了一些代码(我不记得链接,如果我再次发现会发布)。但他们否认UIResponder我认为,然后从那里调用doBadSwizzle()方法,允许他们没有访问AppDelegate的工作。 我不确定具体的实施细节了 –

+1

我想你是指这个职位:http://jordansmith.io/handling-the-deprecation-of-initialize/。我正在他的博客上与乔丹进行讨论,所以如果您有任何补充,请随时加入。谢谢! – CPR