【问题标题】:Swizzling CocoaTouch class in Swift 3.1Swift 3.1 中的 CocoaTouch 类
【发布时间】:2017-03-30 13:35:53
【问题描述】:

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

方法'initialize()'定义了Objective-C类方法'initialize', 不能保证被 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,但我不明白如何在我的代码中使用信息。

【问题讨论】:

标签: ios swift3 xcode8


【解决方案1】:

我有同样的问题并解决它。

我的解决方案

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多