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



我使用 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. 将 swizzling() 方法从私有(private)改为公共(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?

关于ios - Swizzling CocoaTouch 类在 Swift 3.1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43119514/

10-11 04:28