以NSURL
的URLWithString:
为例:
#import <objc/runtime.h>
@implementation NSURL (URLWithStringEncode)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^ {
const char* class_name = class_getName([self class]);
Class metaClass = objc_getMetaClass(class_name);
SEL originalSelector = @selector(URLWithString:);
SEL newSelector = @selector(p_URLWithString:);
Method originalMethod = class_getInstanceMethod(metaClass, originalSelector);
Method newMethod = class_getInstanceMethod(metaClass, newSelector);
BOOL methodAdded = class_addMethod([metaClass class],
originalSelector,
method_getImplementation(newMethod),
method_getTypeEncoding(newMethod));
if (methodAdded) {
class_replaceMethod([metaClass class],
newSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, newMethod);
}
});
}
+ (instancetype)p_URLWithString:(NSString *)URLString {
//TODO:...
return [NSURL p_URLWithString:URLString];
}
@end
相关知识
iOS Method Swizzling
刨根问底Objective-C Runtime(2)- Object & Class & Meta Class