【发布时间】:2019-04-10 20:04:10
【问题描述】:
我有一个带有此代码的 UIViewController:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(@"CLASIC");
}
然后我有一个带有 UIViewController 类别的框架,它以这种方式运行:
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL viewWillAppearSelector = @selector(viewDidAppear:);
SEL viewWillAppearLoggerSelector = @selector(logged_viewDidAppear:);
Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);
Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector);
method_exchangeImplementations(originalMethod, extendedMethod);
});
}
- (void)logged_viewDidAppear:(BOOL)animated
{
[self logged_viewDidAppear:animated];
NSLog(@"SWIZZLED");
}
输出是 SWIZZLED,然后是 CLASIC。
现在我的问题是:如果在我的视图控制器中我评论了 [super viewDidAppear:animated];然后不再调用 swizzled 方法;这是为什么?我理解了大部分方面,但似乎这一方面不知何故滑倒了。
- (void)viewDidAppear:(BOOL)animated
{
// we comment this and this will trigger the swizzled method not being called anymore
//[super viewDidAppear:animated];
NSLog(@"CLASIC");
}
// ========================
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL viewWillAppearSelector = @selector(viewDidAppear:);
SEL viewWillAppearLoggerSelector = @selector(logged_viewDidAppear:);
Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);
Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector);
method_exchangeImplementations(originalMethod, extendedMethod);
});
}
- (void)logged_viewDidAppear:(BOOL)animated
{
[self logged_viewDidAppear:animated];
NSLog(@"SWIZZLED");
}
【问题讨论】:
-
您注释掉了方法调用并且不再调用该方法 - 您还期望什么?
-
@mag_zbc 我评论了super调用,替换当前的swizzled方法和super有什么关系?
标签: ios objective-c swizzling method-swizzling