我的问题不是关于如何浏览,而是此特定代码段中发生的事情:
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)")
}
}
此代码狙击手来自这里:swizzling cocoatouch class
我有以下代码的问题:
// make sure this isn't a subclass
guard self === UIViewController.self else { return }
为什么我们需要检查它是否不是UiviewController的子类?我的情况是,我想将带有视图名称的分析数据发送到Omniture(在ViewWillAppear上)。如果我进行检查,则散发器永远无法正常工作,但是当我评论这一行时,我会得到所需的结果,每个视图控制器都会发送数据。
您所看的示例似乎来自在类initialize
方法中完成此操作的日子,您必须进行检查,或者最终可以运行相同的代码多次(第一次使用子类),这会导致您已经散布的方法。
但是initialize
方法不再允许在Swift中,因此该行不适用。