views:

129

answers:

2

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?

+3  A: 

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
Nathaniel Martin
How do I do that?
Evelyn
As Blaenk said below, make sure to initialize the counter somewhere.
Nathaniel Martin
You just solved my life.
Evelyn
Glad to help! If only everything else in life was so easy....
Nathaniel Martin
+2  A: 

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.

Jorge Israel Peña
Wow! I've been living in the dark all this time! Should've asked this question weeks ago. Thanks. :)
Evelyn