Junior — Middle
What is Swizzling and what are its advantages and disadvantages?
sobes.tech AI
Answer from AI
Swizzling is a technique in Objective-C and Swift that allows dynamically changing method implementations at runtime. It is commonly used to replace the default behavior of system classes.
Advantages:
- Enables adding or modifying functionality without changing the source code.
- Convenient for logging, tracking, bug fixing, or adding cross-cutting functions.
Disadvantages:
- Can lead to unpredictable behavior if used carelessly.
- Difficult to debug and maintain.
- Violates encapsulation and may conflict with future SDK updates.
Example of Swizzling in Objective-C:
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method original = class_getInstanceMethod(self, @selector(viewWillAppear:));
Method swizzled = class_getInstanceMethod(self, @selector(xxx_viewWillAppear:));
method_exchangeImplementations(original, swizzled);
});
}
- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated]; // call the original method
NSLog(@"%@ will appear", NSStringFromClass([self class]));
}
@end
Here, we replace the implementation of viewWillAppear: with our own, adding logging.