Sobes.tech
Junior — Middle

Could you provide an example of applying Swizzling technique in programming?

sobes.tech AI

Answer from AI

Swizzling is a technique in Objective-C and Swift that allows dynamically changing the implementation of methods at runtime. It is commonly used to add or modify the behavior of existing methods without changing the class's source code.

Example of usage: adding logging to calls of the UIViewController method viewDidLoad without inheritance.

#import <objc/runtime.h>

@implementation UIViewController (Logging)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        SEL originalSelector = @selector(viewDidLoad);
        SEL swizzledSelector = @selector(xxx_viewDidLoad);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        method_exchangeImplementations(originalMethod, swizzledMethod);
    });
}

- (void)xxx_viewDidLoad {
    [self xxx_viewDidLoad]; // call the original viewDidLoad
    NSLog(@"viewDidLoad called for %@", self);
}

@end

This approach allows injecting additional logic without modifying the base class.

Could you provide an example of applying Swizzling… - sobes.tech