I’d like to execute a piece of code every 500ms for a total of 10 seconds. I have the code working executing every half a second with this code
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getLevel:) userInfo:nil repeats: YES];
but I cannot seem to figure out how to stop it executing after 10 seconds. The “repeats” argument doesnt seem to allow for a specified time.
Could someone point me in the direction of where I should go with this?
Thanks
Brian
You need to message
invalidateon the NSTimer that scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: gives you. For example assign the NSTimer that method returns to you in a property or iVar of your class and after 10 seconds callinvalidateon it.Example:
.h:
.m:
You could avoid another
NSTimerif you want by implementing some kind offinishflag and track how many times you messaged thegetLevelmethod, since it’s every .5 seconds, that’ll be 20 times.But I would rather 2
NSTimerobjects because you know it’s 10 seconds regardless of the other timer, which you might decide to change, up or down it’s frequency…