Home > Software design >  Swizzling [NSObject initialize] method to log each class intantiation
Swizzling [NSObject initialize] method to log each class intantiation

Time:08-08

Basically, I want to print each time a class object is instantiated. The following code shows the intent.

@interface NSObject (ILogger)
  (void)initialize;
@end

@implementation NSObject (ILogger)
  (void)initialize
{
    NSLog(@"Initializing %s", class_getName([self class]));
}
@end

This does not work because NSObject already has a initialize method so this approach results in undefined behavior. The compiler also warns about the issue: warning: category is implementing a method which will also be implemented by its primary class

One idea would be to somehow swizzle [NSObject initialize] and do the logging. How do I do that safely?

EDIT:

Maybe I'm using the wrong terminology but the goal is to know if a class is used at all in the app. If many objects of a class are created, there is no need to log every time, once is sufficient.

CodePudding user response:

The enter image description here

CodePudding user response:

I think it's possible to do this with breakpoint if only need logging, I've not tested it with initialize, but does works on my case with dealloc, note that it might print a lot more than you actually needed and slow down performance:

  • In Xcode, go to the Breakpoint navigator (Cmd 8)
  • At the bottom-left on the screen, tap ' ', then select "Symbolic Breakpoint..." from the menu
  • Fill the form:
    • Symbol: -[NSObject initialize]
    • Action: Select "Log Message"
    • Enter: --- init @(id)[$arg1 description]@ @(id)[$arg1 title]@
    • Select "Log message to console"
    • Check "Automatically continue after evaluating actions" so Xcode does not stop at the breakpoint
  • Related