记录项目中所有 UIViewController 的类名 [英] Logging the class name of all UIViewControllers in a project
问题描述
我们收到了一个来自外包的巨大项目,我们正试图修复"这个项目.项目中有数百个视图控制器.我们的目标是轻松确定我们当前在设备上查看的类别.
We have received a HUGE project from outsourcing that we are trying to "repair". There are hundreds of view controllers within the project. Our goal is to easily determine which class we are currently looking at on the device.
我们的解决方案(不起作用,因此是 SO 问题)如下.
Our solution (which didn't work, hence the SO question) follows.
通过一个类别覆盖 UIViewController 的 viewDidAppear 方法:
Override the viewDidAppear method of UIViewController via a category with this:
-(void)viewDidAppear:(BOOL)animated
{
NSLog(@"Current View Class: %@", NSStringFromClass(self.class));
[self viewDidAppear:animated];
//Also tried this:
//[super viewDidAppear:animated];
}
此类别将放在项目的 .pch 中.
This category would be put in the .pch of the project.
这不需要在数百个视图控制器中放入额外的代码,并且可以轻松打开和关闭.它没有用,因为正如我们现在了解到的,<meme>one 不会简单地通过类别覆盖现有方法</模因>.
This would require no extra code to be put in the hundreds of View Controllers and be easily turned on and off. It didn't work because, as we've learned now, <meme>one does not simply override an existing method via category</meme>.
我们错过了什么?!?
推荐答案
答案是调配方法!这是我们想出的:
The answer is to swizzle the methods! Here is what we came up with:
#import "UIViewController+Logging.h"
#import <objc/runtime.h>
@implementation UIViewController (Logging)
-(void)swizzled_viewDidAppear:(BOOL)animated
{
NSLog(@"Current View Class: %@", NSStringFromClass(self.class));
[self swizzled_viewDidAppear:animated];
}
+ (void)load
{
Method original, swizzled;
original = class_getInstanceMethod(self, @selector(viewDidAppear:));
swizzled = class_getInstanceMethod(self, @selector(swizzled_viewDidAppear:));
method_exchangeImplementations(original, swizzled);
}
@end
这篇关于记录项目中所有 UIViewController 的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!