user688262
user688262

Reputation: 211

Xcode, iOs Development: Log every Controllername

I currently work into a big project that consists of lots of classes. Can you imagine a way to get a log message with the name of the controller everytime a controller is loaded? The background is following: When I have to fix a bug, I spend quite much time with searching for the corresponding source code. It would help me a lot if I click through the app in the simulator and see which class I am currently in.

Thanks in advance.

Upvotes: 1

Views: 289

Answers (3)

Artur Ozierański
Artur Ozierański

Reputation: 1177

In big project you probably don't want to change all UIViewControllers to subclass with overridden -viewDidLoad method. You can change implementation of -viewDidLoad at the runtime by using method swizzling. By this way you can add name logging to -viewDidLoad with saving original implementation. Check out this: 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

Upvotes: 3

Oliver
Oliver

Reputation: 23510

To do this easily, you may :

1- create a UIViewControllerEnhanced view controller that inherits from UIViewController
2- Override its viewDidLoad method (or any init method depending on what you want) like this :

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

3- in your project, replace in all your view controller the possible UIViewController inheritance by UIViewControllerEnhanced class.

That's it :-)

Upvotes: 1

Sudesh Kumar
Sudesh Kumar

Reputation: 569

Use this one in all classes:

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

}

Upvotes: 0

Related Questions