-3

What I am attempting to do is increment a variable every second, minute, etc. that is elapsed when my iOS application is running.

I have looked around and NSTimer seems to be one option, but I'm not sure how to implement it.

So far, all I have is;

NSTimer *time;

And that is only if NSTimer is the most appropriate option to use here.

Hemang
  • 26,840
  • 19
  • 119
  • 186
  • 2
    It may help if you tell us what you are actually trying to achieve as the end goal. Maybe there are better ways to do what you want to do. – Allan Spreys Dec 13 '14 at 05:56
  • Please do some searching. There are tons of answers on this site about timers where you can see how people implemented them. – rdelmar Dec 13 '14 at 06:02

1 Answers1

1

You have NSTimer *timer; declared alredy, so you need to add the following class method in the any AppDelegate Method, executing which you want to start the timer (Say for example -didFinishLaunchingWithOptions)

timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self
                                       selector:@selector(incrementVariable:) 
                                       userInfo:nil repeats:YES];

Also, you need to invalidate the timer wherever to want to stop it using:

[timer invalidate];

Now, say you have your Global variable variableName which you want to increment every second. In order to do that, you have to implement the selector you passed in scheduledTimerWithTimeInterval method.

- (void)incrementVariable:(NSTimer *)timer{
    variableName++;
}

Hope this helps.

Anon
  • 623
  • 3
  • 10
  • And yes, if you describe what you are trying to achieve, there may be a better approach for doing this; as mentioned by @VladSpreys – Anon Dec 13 '14 at 06:18
  • Fantastic answer, and would it be appropriate to declare the variable 'timer' from within the AppDelegate method of my choosing as well? The end goal here is to be able to increment a variable that tracks points when the application is open. So the player's score increments every second, minute, etc. that the application is open. – user4334739 Dec 13 '14 at 15:58
  • 1
    Solved. I went ahead and added the timer to - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions. – user4334739 Dec 13 '14 at 19:15
  • @user4334739 I am glad it helped. You can accept the answer if it did. – Anon Dec 13 '14 at 19:59