@interface Person : NSObject
@end
@implementation Person
@end
@interface Person (swizzleExample)
@end
@implementation Person (swizzleExample)
- (void)swizzleExample {
Class class = [self class];
SEL originalSelector = @selector(originalMethod);
SEL replacedSelector = @selector(replacedMethod);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method replacedMethod = class_getInstanceMethod(class, replacedSelector);
BOOL success = class_addMethod(class,
originalSelector,
method_getImplementation(replacedMethod),
method_getTypeEncoding(replacedMethod));
if (success) {
class_replaceMethod(class,
replacedSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, replacedMethod);
}
}
- (void)originalMethod {
NSLog(@"方法名为 originalMethod,其 _cmd 的值为:%@",[NSString stringWithFormat:@"*** -%@", NSStringFromSelector(_cmd)]);
}
- (void)replacedMethod {
NSLog(@"方法名为 replacedMethod,其 _cmd 的值为:%@",[NSString stringWithFormat:@"*** -%@", NSStringFromSelector(_cmd)]);
}
@end
Person *personModel = [[Person alloc] init];
NSLog(@"## swizzle 之前,调用 originalMethod 的打印信息:");
[personModel originalMethod];
[personModel replacedMethod];
[personModel swizzleExample];
NSLog(@"## swizzle 之后,调用 originalMethod 的打印信息:");
[personModel originalMethod];
[personModel replacedMethod];
2022-03-03 10:34:36.975410+0800 dsadasdasdsa[14591:17348825] ## swizzle 之前,调用 originalMethod 的打印信息:
2022-03-03 10:34:36.975549+0800 dsadasdasdsa[14591:17348825] 方法名为 originalMethod,其 _cmd 的值为:*** -originalMethod
2022-03-03 10:34:36.975633+0800 dsadasdasdsa[14591:17348825] 方法名为 replacedMethod,其 _cmd 的值为:*** -replacedMethod
2022-03-03 10:34:36.975883+0800 dsadasdasdsa[14591:17348825] ## swizzle 之后,调用 originalMethod 的打印信息:
2022-03-03 10:34:36.975991+0800 dsadasdasdsa[14591:17348825] 方法名为 replacedMethod,其 _cmd 的值为:*** -originalMethod
2022-03-03 10:34:36.976091+0800 dsadasdasdsa[14591:17348825] 方法名为 originalMethod,其 _cmd 的值为:*** -replacedMethod