Search code examples
objective-ccounterclass-method

Count number of time a class method is called in Objective-C


There is already a topic there showing how to count the number of times a instance method is called within the program: Count the number of times a method is called in Cocoa-Touch?

The code described there is working well with an instance method, but it isn't working with a class method. Somebody knows how to do ?


Solution

  • Just use a static int:

    +(void)myClassMethod{
      static int count = 0;
      count++;
    
      //your code
    }
    

    Edit: This is pretty stupid now I think of it since you can't retrieve the count from outside the method.
    Still you can log it or send the value with a notification or any other way...

    Edit 2:
    Or you could use another class method to store your counter:

    +(int)countAfterIncrement:(BOOL)increment{
      static int count = 0;
      if (increment)
        count ++;
      return count;
    }
    
    +(void)myClassMethod{
          [MyClass countAfterIncrement:YES];
    
          //your code
     }
    

    To retrieve the value just use [MyClass countAfterIncrement:NO];