Swift 3.1中的Swizzling CocoaTouch类

时间:2017-03-30 13:35:53

标签: ios swift3 xcode8

我在XCode 8.3中使用Swift 3.1并看到该警告:

  

方法'初始化()'定义Objective-C类方法'初始化',   这不保证由Swift调用,将被禁止   在未来版本中

我使用Swizzling CocoaTouch class并且该部分存在问题:

extension UIViewController {

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

    // MARK: - Method Swizzling

    func proj_viewWillAppear(animated: Bool) {
        self.proj_viewWillAppear(animated: animated)

        let viewControllerName = NSStringFromClass(type(of: self))
        print("viewWillAppear: \(viewControllerName)")
    } 
 }

如何重写代码的那一部分?

open override class func initialize()

修复新警告?

我看到了link,但我不明白如何在代码中使用信息。

1 个答案:

答案 0 :(得分:3)

我有同样的问题并修复它。

我的解决方案

1。将swizzling()方法从私有

更改为public
public let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
    let originalMethod = class_getInstanceMethod(forClass, originalSelector)
    let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
    method_exchangeImplementations(originalMethod, swizzledMethod)
}

2。删除extension UIViewController

处的initialize()方法
//    open override class func initialize() {
//        // make sure this isn't a subclass
//        guard self === UIViewController.self else { return }
//        swizzling(self)
//    }

3。在AppDelegate :: didFinishLaunchingWithOptions

添加swizzling()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // some code

    swizzling(UIViewController.self)

    return true
}

这是简单易行的解决方案。 (这不是优雅的)

如果您想了解更多信息,请参阅:  Swift 3.1 deprecates initialize(). How can I achieve the same thing?