728x90
Method Swizzling
- Runtime 시점에 기존 method를 다른 method로 바꾸어 실행하는 것
- 목적
- 특정 기능을 부모 클래스와 서브 클래스에 모두 적용시키고 싶을 때
- 앱에 분석 기능 통합 EX) life cycle 콜백에 logging 기능
- 주의
- iOS버전이 올라가면 문제 생길 가능성 있음
swizzle method 구현
- origin method와 swizzle해서 교체할 메서드를 selector로 생성 후, class_getInstanceMethod를 통해 Method 객체로 가져옴
- method_exchangeImplementations로 두 메서드의 구현을 바꾼다.
- 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
'Swift' 카테고리의 다른 글
[Swift] Weak vs Unowned Reference (0) | 2022.08.20 |
---|---|
[Swift] 특정 class 상속받아야만 protocol을 채택하도록 제약 걸기 (0) | 2022.07.16 |
[Swift] 프로토콜 지향 프로그래밍 (Protocol Oriented Program) (0) | 2022.06.19 |
[Swift] 왜 struct에선 mutating을 사용해야하는가? (0) | 2022.06.19 |
[Swift] 메모리 구조 (0) | 2022.06.06 |
댓글