swift

Method Swizzling

motosw3600 2021. 12. 10. 08:51

Method Swizzling

  • Method Swizzling이란 원래의 메소드를 runtime때 다른 메소드로 바꿔 실행하는것
  • 원하는 메소드로 바꾸면 메소드를 호출하기 전에 사용자 추적, 특정 기능을 수행할 수 있지만 버그 발생 가능

언제 사용할까?

  • 서브 클래스를 만들어 사용하는것 보다 런타임때 특정 기능을 바꿔 사용할 때
  • 특정 기능을 클래스&서브 클래스 모두 한번에 적용시키고 싶을 때
  • 앱의 분석기능을 통합할 때
  • 해당 메서드 대신 다른 메서드가 실행되도록 바꿀 때

사용 예제

extension UIViewController {
    class func swizzleMethod() {
        let originalSelector = #selector(UIViewController.viewDidLoad)
        let swizzledSelector = #selector(UIViewController.swizzleViewDidLoad)
        
        guard let originMethod = class_getInstanceMethod(UIViewController.self, originalSelector),
              let swizzeldMethod = class_getInstanceMethod(UIViewController.self, swizzledSelector) else { return }
        method_exchangeImplementations(originMethod, swizzeldMethod)
    }
    
    @objc func swizzleViewDidLoad() {
        print("swizzleViewDidLoad")
    }
}

 

  • AppDelegate단에서 swizzling 적용
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UIViewController.swizzleMethod()
        return true
    }
}

 

  • viewDidLoad실행 시 콘솔창 메세지 확인 가능

 

'swift' 카테고리의 다른 글

struct, class, enum  (0) 2021.12.14
URLSession  (0) 2021.12.10
Layout Update Method  (0) 2021.12.09
KVC, KVO  (0) 2021.12.08
Properties  (0) 2021.12.08