2011-11-07 39 views
1

我目前的工作成了一个大项目,包括大量的类。每次加载控制器时,您能想象一种获取带有控制器名称的日志消息的方法吗? 的背景下:当我有修复一个bug,我花了相当多的时间与搜索相应的源代码。这将帮助我很多,如果我通过点击在模拟器应用程序,看看我目前在哪个班。的Xcode,iOS开发:登录每Controllername

在此先感谢。

回答

1

为了容易做到这一点,则可能:

1-创建从UIViewController中
2-继承覆盖其viewDidLoad方法的UIViewControllerEnhanced视图控制器(或任何初始化方法取决于你想要的)如下:

- (void) viewDidLoad { 
    [super viewDidLoad]; 
    NSLog(@"viewDidLoad for class %@", self.className); 
} 

3-在你的项目ct,在所有视图控制器中用UIViewControllerEnhanced类替换可能的UIViewController继承。

就是这样:-)

+0

谢谢!但是,我们有几百个班。没有编辑每个现有文件没有办法做到这一点? – user688262

+0

@ user688262:我没有看到一个simplier方式。但是这个编辑很简单。只是搜索所有“:UIViewController的”在你的文件(你应该只得到.h文件),并与替换“:UIViewControllerEnhanced”。这可能很容易。 – Oliver

0

使用这一个在所有类:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSLog(@"Working class is %@",self); 

} 
3

在你可能不希望改变这一切UIViewControllers与重写-viewDidLoad方法来继承大项目。您可以使用方法调整来更改运行时的-viewDidLoad的实现。通过这种方式,您可以将名称日志记录添加到-viewDidLoad并保存原始实现。看看这个:http://mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html

#import <objc/runtime.h> 

@implementation UIViewController (LoadLogging) 

void MethodSwizzle(Class c, SEL origSEL, SEL overrideSEL); 

- (void)override_viewDidLoad { 

    [self override_viewDidLoad]; 

    NSLog(@"%@ loaded", self); 
} 

+ (void)load 
{ 
    MethodSwizzle(self, @selector(viewDidLoad), @selector(override_viewDidLoad)); 
} 


void MethodSwizzle(Class c, SEL origSEL, SEL overrideSEL) 
{ 
    Method origMethod = class_getInstanceMethod(c, origSEL); 
    Method overrideMethod = class_getInstanceMethod(c, overrideSEL); 
    if(class_addMethod(c, origSEL, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) 
    { 
     class_replaceMethod(c, overrideSEL, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); 
    } 
    else 
    { 
     method_exchangeImplementations(origMethod, overrideMethod); 
    } 
} 

@end