How to increment a variable and overwrite the old one?
I'm new to Objective C, and I'm quite confused that the method:
-(void)increment
{
count = count+1;
}
doe开发者_StackOverflow社区sn't increment the variable count on any method call, but just sets the variable on "1", no matter how often i call the method. This is different in Objective-C isnt it? In other languages it´s pretty basic.
Help would be great, thanks anyway guys.
If that is not an instance variable, you need to statically initialize it. Try this:
-(void)increment {
static int count = 0;
count = count + 1; // Alternatively written as count++;
}
If you want it to be an instance variable, you need to declare it in your header file. In that case, do this instead:
@interface SomeClass : NSObject {
int count;
}
Then your increment
method should work properly.
精彩评论