Câu hỏi phỏng vấn Objective-C
Câu hỏi

Explain method swizzling...

Câu trả lời

Method Swizzling in Objective-C

Method swizzling is a technique in Objective-C that allows you to swap the implementation of one method with another. This is done by modifying the method dispatch table (also known as the method resolution order) at runtime. By swapping the implementations, you can change the behavior of a class or an instance of a class without modifying the original code.

When to Use Method Swizzling

  1. Debugging and logging: You can use method swizzling to add logging or debugging functionality to methods without modifying the original implementation.

  2. Extending system classes: If you want to add functionality to a system class (e.g., UIViewController, NSString) without subclassing, method swizzling can be a solution.

  3. Aspect-oriented programming (AOP): Method swizzling can be used to implement AOP concepts, such as method interception, logging, and security checks.

  4. Monkey patching: Method swizzling can be used to "monkey patch" or override the behavior of a class at runtime, which can be useful for testing or fixing issues in third-party libraries.

  5. Implementing design patterns: Method swizzling can be used to implement design patterns like the decorator pattern or the proxy pattern.

Example of Method Swizzling

#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(my_viewDidLoad);
 ...
expert

expert

Gợi ý câu hỏi phỏng vấn

middle

When to use NSArray vs NSSet ?

junior

What are blocks and how are they used?

middle

What is the difference between NSDictionary and NSMutableDictionary ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào