views:

55

answers:

3

Hi!

I have a button in my App called myButton, what I what to do is really simple. I want to have an integer that adds one to itself every time the Button is pushed. Here's what the code looks like right now:

- (IBAction)myButton {  
NSLog(@"Button was pushed WOHHOP");
}

This is inside my .m file, so do I need to declare an integer inside my .h file? I just want to Log the value of it inside this button action so that as I push it I can see the number increase by one every time.

Any advice would help, Thank you!

+1  A: 

You can also declare a static variable:

- (IBAction)myButton {
    static NSUInteger counter = 0;
    counter++;
    NSLog(@"Button was pushed WOHHOP. Counter: %u", counter);
}

But note that in this case, the counter variable will be shared among all instances of this class. This might not be a problem in this case but it can be confusing. A real instance variable is usually the better way to go.

Ole Begemann
Thank you, this is exactly what I needed, just out of curiosity do I need to "release" this variable once the app comes to an end?
Pete Herbert Penito
No. But please note the text I just added to my answer.
Ole Begemann
+4  A: 

i would use an instance variable by default:

@interface MONClass : MONSuperClass
{
    NSUInteger clicks;
}

@end

@implementation MONClass

- (id)init {
    self = [super init];
    if (0 != self) {
        clicks = 0;
    }
    [return self];
}

- (IBAction)myButton:(id)sender
{
#pragma unused(sender)
    ++clicks;
    NSLog(@"Button was pushed %i times WOHHOP", clicks);
}
Justin
What is the `#pragma` for?
Emil
`- (IBAction)method:(id)sender` is the method signature an `IBAction` should take. in this case, `sender` is unused. `#pragma unused(sender)` silences the warning emitted by the compiler (depending on the warnings you've enabled).
Justin
+1  A: 

The third option is to just use a global variable. Declare:

int counter = 0;

between the imports and the implementation in any .m file (but only one); declare:

extern int counter;

in the header of any file where you want to use this counter. And use:

counter++;

from anywhere (any function, method, object or class), and access the counter across the entire application.

Note that the use of global variables does not scale well to large apps or reusable components, so their use is usually discouraged. Use instance variables, or maybe class or method static locals, instead, if at all possible.

hotpaw2