如何实现swift swift 3.0的方法?

如何实现swift swift 3.0的方法?,第1张

如何实现swift swift 3.0的方法

首先,

dispatch_once_t
在Swift 3.0中不可用。您可以选择两种选择:

  1. 全局变量

  2. 静态财产

    struct
    enum
    class

对于不同的目的,您必须使用不同的实现方式
  • 令人毛骨悚然的CocoaTouch类,例如UIViewController;
  • 定制的Swift类;

令人毛骨悚然的CocoaTouch类

例如混写

viewWillAppear(_:)
UIViewController
使用全局变量

private let swizzling: (UIViewController.Type) -> () = { viewController in    let originalSelector = #selector(viewController.viewWillAppear(_:))    let swizzledSelector = #selector(viewController.proj_viewWillAppear(animated:))    let originalMethod = class_getInstanceMethod(viewController, originalSelector)    let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector)    method_exchangeImplementations(originalMethod, swizzledMethod) }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)")    }  }
自定义Swift类

要对Swift类使用方法混乱,必须满足两个要求(有关更多详细信息):

  • 包含要混淆的方法的类必须扩展
    NSObject
  • 您想要混淆的方法必须具有
    dynamic
    属性

自定义Swift基类的示例混淆方法

Person

class Person: NSObject {    var name = "Person"    dynamic func foo(_ bar: Bool) {        print("Person.foo")    }}class Programmer: Person {    override func foo(_ bar: Bool) {        super.foo(bar)        print("Programmer.foo")    }}private let swizzling: (Person.Type) -> () = { person in    let originalSelector = #selector(person.foo(_:))    let swizzledSelector = #selector(person.proj_foo(_:))    let originalMethod = class_getInstanceMethod(person, originalSelector)    let swizzledMethod = class_getInstanceMethod(person, swizzledSelector)    method_exchangeImplementations(originalMethod, swizzledMethod)}extension Person {    open override class func initialize() {        // make sure this isn't a subclass        guard self === Person.self else { return }        swizzling(self)    }    // MARK: - Method Swizzling    func proj_foo(_ bar: Bool) {        self.proj_foo(bar)        let className = NSStringFromClass(type(of: self))        print("class: (className)")    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4897922.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存