Skip to content

Instantly share code, notes, and snippets.

@bumaociyuan
Created January 29, 2018 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bumaociyuan/f64d77c1ec374f71e78502d272c30a36 to your computer and use it in GitHub Desktop.
Save bumaociyuan/f64d77c1ec374f71e78502d272c30a36 to your computer and use it in GitHub Desktop.
swizzle function
@interface NSObject (hook)
+ (void)switchClassFuction:(NSString *)originalSelectorName swizzledSelector:(NSString *)swizzledSelectorName;
+ (void)switchInstanceFuction:(NSString *)originalSelectorName sel2:(NSString *)swizzledSelectorName;
@end
@implementation NSObject (hook)
+ (void)switchClassFuction:(NSString *)originalSelectorName swizzledSelector:(NSString *)swizzledSelectorName {
Class class = object_getClass((id)self);
SEL originalSelector = NSSelectorFromString(originalSelectorName);
SEL swizzledSelector = NSSelectorFromString(swizzledSelectorName);
Method originalMethod = class_getClassMethod(class, originalSelector);
Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
+ (void)switchInstanceFuction:(NSString *)originalSelectorName sel2:(NSString *)swizzledSelectorName {
Class class = [self class];
SEL originalSelector = NSSelectorFromString(originalSelectorName);
SEL swizzledSelector = NSSelectorFromString(swizzledSelectorName);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment