views:

437

answers:

1

Every 1/16 of a second, I have an NSTimer that fires, calling a method each time. I want to create a static integer that is increased by '1' each time the method is called, once the static integer is equal to '16', I wish to call another method and reset the static integer to '0'.

Any insight is greatly appreciated. (Language is Obj-C)

+4  A: 

So declare it as a static int...

static int myCounter;
@implementation SomeClass

- (id) init {
  if (self = [super init]) {
    myCounter = 0;
    NSTimer * someTimer = [NSTimer scheduledTimerWithTimeInterval:(1/16) target:self selector:@selector(fireTimer:) userInfo:nil repeats:YES];
  }
  return self;
}

- (void) fireTimer:(NSTimer *)aTimer {
  myCounter++;
  if (myCounter == 16) {
    [self doSomeMethod];
    myCounter = 0;
  }
}

@end
Dave DeLong
I think he needs the method to change every second, which this won't accomplish. You could pass a function pointer (if obj C has them) as a second parameter, and just call that.
Hooked
@Hooked that's not possible. Once a timer's been created, you can't change which selector it fires. So the simple solution is to have an if() statement in the fire method and then branch from there.
Dave DeLong
@Hooked and about passing a selector as the second parameter, you can't do that either. NSTimer fire methods have to have a very specific signature (return void, single NSTimer* parameter).
Dave DeLong