开发者

How to increment a variable and overwrite the old one?

开发者 https://www.devze.com 2023-01-29 00:42 出处:网络
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 s

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消