Evelyn
Evelyn

Reputation: 2656

Count the number of times a method is called in Cocoa-Touch?

I have a small app that uses cocos2d to run through four "levels" of a game in which each level is exactly the same thing. After the fourth level is run, I want to display an end game scene. The only way I have been able to handle this is by making four methods, one for each level. Gross.

I have run into this situation several times using both cocos2d and only the basic Cocoa framework. So is it possible for me to count how many times a method is called?

Upvotes: 2

Views: 1345

Answers (2)

Nathaniel Martin
Nathaniel Martin

Reputation: 2092

Can you just increment an instance variable integer every time your method is called?

I couldn't format the code in a comment, so to expound more:

In your header file, add an integer as a instance variable:

@interface MyObject : NSObject { 
   UIInteger myCounter; 
} 

And then in your method, increment it:

@implementation MyObject
    - (void)myMethod { 
      myCounter++; 
      //Do other method stuff here 
      if (myCounter>3){ 
          [self showEndGameScene]; 
      } 
     }

@end 

Upvotes: 3

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38616

I don't know if your way is the best way to do it, or if mine is, but like Nathaniel said, you would simply define an integer to hold the count in your @interface:

@interface MyClass : NSObject {
    int callCount;
}

Then the method can increment this by doing:

- (void) theLevelMethod {
   callCount++;
   // some code
}

Make sure you initialize the callCount variable to 0 though, in your constructor or the equivalent of viewDidLoad. Then in the code that checks the count you can check:

if (callCount == 4) {
   // do something, I guess end scene
}

Then again, I guess you can simply do something like this:

for (int i = 0; i < 4; i++) {
   [self theLevelMethod];
}

[self theEndScene];

I don't know how your game logic works, but I guess that would work.

Sorry if I misunderstood your question.

Upvotes: 2

Related Questions