メソッドの入れ替えがどのように機能するかをよりよく理解するために、この記事に従っています。次のようなメイン ビュー コントローラー (これは新しいプロジェクトです) があります。
#import "GLViewController.h"
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [UIViewController class];
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
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);
}
});
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}
@end
@implementation GLViewController
-(void)viewWillAppear:(BOOL)animated
{
NSLog(@"glviewappear");
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
これを実行すると、glviewappear が出力され、削除すると
-(void)viewWillAppear:(BOOL)animated
{
NSLog(@"glviewappear");
}
次に、それは印刷され viewWillAppear: <GLViewController: 0x9d11a90>
ます。私のプロジェクトは、これらの両方の方法で起動できる必要があります。これを行う方法はありますか?