Integers in IPhone App
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 r开发者_如何学运维ight 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!
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);
}
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.
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.
精彩评论