iOS App生命周期&事件响应链

73 阅读1分钟

从Main函数开始

从main函数开始。

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

事件响应链

UIControl: UIView, UIView: UIResponder ,

UIApplication.shared sendEvent => Window的subviews

执行流总览

Main函数之后,App的生命周期,事件响应链

UIEvent.touches UITouch

应用场景:监听所有的事件,进行事件点击埋点切面编程

func exchangeSendEvent() {
    // 原方法与替换方法
    guard
        let originalMethod = class_getInstanceMethod(UIApplication.self, #selector(sendEvent(:))),
        let swizzledMethod = class_getInstanceMethod(UIApplication.self, #selector(yt_sendEvent(:))) else {
        return
    }
    if class_addMethod(forClass, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) {
        class_replaceMethod(forClass, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
}

extension UIApplication {
    func yt_sendEvent(_ event: UIEvent) {
        yt_sendEvent(event)
        track("event")
    }
}