init
所以第二种方法是正确的。我怀疑你刚刚犯了一个小错误,也许在你的
@selector
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface MyOldController: NSObject
- (instancetype)initWithInt:(NSInteger)x
@end
@implementation MyOldController
- (instancetype)initWithInt:(NSInteger)x
{
self = [super init];
if (self) {
NSLog(@"init");
}
return self;
}
@end
@implementation MyOldController(Swizzle)
+ (void)load {
[MyOldController swizzleMethods];
}
+ (void)swizzleMethods {
method_exchangeImplementations(class_getInstanceMethod(self, @selector(initWithInt:)), class_getInstanceMethod(self, @selector(initWithInt_swizzle:)));
}
- (instancetype)initWithInt_swizzle:(NSInteger)x
{
self = [super init];
if (self) {
NSLog(@"init_swizzle");
}
return self;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyOldController *controller = [[MyOldController alloc] initWithInt:1];
NSLog(@"%@", controller);
}
return 0;
}
按预期打印:
2018-06-21 12:23:14.431936-0400 test[30981:401466] init_swizzle
2018-06-21 12:23:14.432172-0400 test[30981:401466] <MyOldController: 0x10051ee10>