Giải thích method swizzling. Khi nào nên sử dụng nó trong Objective-C?
Giải thích method swizzling. Khi nào nên sử dụng nó trong Objective-C?
Method swizzling là kỹ thuật hoán đổi cài đặt (IMP) của hai phương thức lúc chạy nhờ runtime Objective-C (method_exchangeImplementations).
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t once;
dispatch_once(&once, ^{
Method orig = class_getInstanceMethod(self, @selector(viewDidAppear:));
Method swz = class_getInstanceMethod(self, @selector(xyz_viewDidAppear:));
method_exchangeImplementations(orig, swz);
});
}
- (void)xyz_viewDidAppear:(BOOL)animated {
[self xyz_viewDidAppear:animated]; // GỌI LẠI bản gốc (đã hoán đổi tên)
NSLog(@"Hiển thị: %@", NSStringFromClass([self class]));
}
@end
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.