본문 바로가기
Swift

[Swift] Method Swizzling

by Sky Titan 2022. 7. 9.
728x90
 

Swift) Method Swizzling을 알아보자

안녕하세요 :) 소들입니다 오랜만의 포스팅이네요 엉엉 😱 퇴사 후 하루도 못 쉬다가 처음으로 4일 간 휴식을 취하고 왔읍니다..! 영양가 없는 TMI는 집어치우고 오늘 공부할 것은 바로바로 Method

babbab2.tistory.com

Method Swizzling

  • Runtime 시점에 기존 method를 다른 method로 바꾸어 실행하는 것
  • 목적
    • 특정 기능을 부모 클래스와 서브 클래스에 모두 적용시키고 싶을 때
    • 앱에 분석 기능 통합 EX) life cycle 콜백에 logging 기능
  • 주의
    • iOS버전이 올라가면 문제 생길 가능성 있음

 

swizzle method 구현

  1. origin method와 swizzle해서 교체할 메서드를 selector로 생성 후, class_getInstanceMethod를 통해 Method 객체로 가져옴
  2. method_exchangeImplementations로 두 메서드의 구현을 바꾼다.
  3. application(_: didFinishLaunchingWithOptions:)에서 호출해준다.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UIViewController.swizzle()

        return true
    }

extension UIViewController {
    static func swizzle() {
        let originSelector = #selector(viewDidLoad)
        let swizzleSelector = #selector(swizzleViewDidLoad)
        guard let originMethod = class_getInstanceMethod(UIViewController.self, originSelector),
              let swizzleMethod = class_getInstanceMethod(UIViewController.self, swizzleSelector) else { return }
        
        method_exchangeImplementations(originMethod, swizzleMethod)
    }
    
    @objc
    func swizzleViewDidLoad() {
        print("swizzleViewDidLoad")
    }
}

 

결과 예시

class ViewController: TSViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewDidLoad")
    }
    
}

728x90

댓글