Ios UIViewController方法Swizzing不工作
我正在使用UIViewController上的一个类别跨多个ViewController快速切换ViewWillDisplay:方法Ios UIViewController方法Swizzing不工作,ios,objective-c,method-swizzling,Ios,Objective C,Method Swizzling,我正在使用UIViewController上的一个类别跨多个ViewController快速切换ViewWillDisplay:方法 @implementation UIViewController (Tracking) +(void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ Class class = [self class]; SEL
@implementation UIViewController (Tracking)
+(void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xx_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);
}
});
}
-(void)xx_viewWillAppear:(BOOL)animated
{
[self xx_viewWillAppear:animated];
NSLog(@"VC loaded");
}
@end
当我从故事板加载初始VC时,swizzled方法从未被调用。仅当VC中的viewWillAppear方法被注释掉时,才会调用它。但是,当我删除类别并将代码移动到单个VC中时,两个方法都被调用
#import "ViewController.h"
#import "UIViewController+Tracking.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)viewWillAppear:(BOOL)animated
{
NSLog(@"Inside Controller1");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
如果要在VC中显示视图,可以实现它吗?如果没有,我该如何处理这个问题,如果我需要在VC的视图中编写一些代码,那么将出现?您需要在
视图中调用super
将出现:
来自ViewController
,否则基类(UIViewController
)中的方法将不会执行,这就是您所使用的方法
将出现以下版本的视图:
应提供预期结果:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"Inside Controller1");
}
只尝试
方法\u exchangeImplementations
,不添加,因为该方法已经存在于扩展的一部分中。此外,您正在从基类切换该方法,在自定义类中重写它意味着您需要调用super
,以获得swizzled方法executed@Cristik我使用的是一个类别,而不是VC的子类。@interface ViewController()
-似乎您正是我所说的子类:)您正在旋转视图将出现:
在UIViewController
上,并覆盖ViewController
子类。你需要从子类中调用super,这在苹果的。