How do I use NSTimer? - objective-c

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
How do I use an NSTimer? Can anyone give me step by step instructions?

Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:
Timer Programming Topics for Cocoa
Threading Programming Guide
For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:
Timers
Using Timers
For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management". From the article, creating a scheduled, non-repeating timer can be done something like this:
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:#selector(targetMethod:)
userInfo:nil
repeats:NO];
This will create a timer that is fired after 2.0 seconds and calls targetMethod: on self with one argument, which is a pointer to the NSTimer instance.
If you then want to look in more detail at the method you can refer back to the docs for more information, but there is explanation around the code too.
If you want to stop a timer that is one which repeats, (or stop a non-repeating timer before it fires) then you need to keep a pointer to the NSTimer instance that was created; often this will need to be an instance variable so that you can refer to it in another method. You can then call invalidate on the NSTimer instance:
[myTimer invalidate];
myTimer = nil;
It's also good practice to nil out the instance variable (for example if your method that invalidates the timer is called more than once and the instance variable hasn't been set to nil and the NSTimer instance has been deallocated, it will throw an exception).
Note also the point on Memory Management at the bottom of the article:
Because the run loop maintains the timer, from the perspective of memory management there's typically no need to keep a reference to a timer after you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.

there are a couple of ways of using a timer:
1) scheduled timer & using selector
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:#selector(onTick:)
userInfo: nil repeats:NO];
if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
to stop the timer you call the timer's -invalidate method: [t invalidate];
As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:
[self performSelector:#selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;
2) self-scheduled timer
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:#selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second
3) unscheduled timer & using invocation
NSMethodSignature *sgn = [self methodSignatureForSelector:#selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:#selector(onTick:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:YES];
and after that, you start the timer manually whenever you need like this:
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
And as a note, onTick: method looks like this:
-(void)onTick:(NSTimer *)timer {
//do smth
}

Something like this:
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
target: self
selector: #selector(handleTimer:)
userInfo: nil
repeats: YES];

#import "MyViewController.h"
#interface MyViewController ()
#property (strong, nonatomic) NSTimer *timer;
#end
#implementation MyViewController
double timerInterval = 1.0f;
- (NSTimer *) timer {
if (!_timer) {
_timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:#selector(onTick:) userInfo:nil repeats:YES];
}
return _timer;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)onTick:(NSTimer*)timer
{
NSLog(#"Tick...");
}
#end

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:#selector(timerCalled) userInfo:nil repeats:NO];
-(void)timerCalled
{
NSLog(#"Timer Called");
// Your Code
}

The answers are missing a specific time of day timer here is on the next hour:
NSCalendarUnit allUnits = NSCalendarUnitYear | NSCalendarUnitMonth |
NSCalendarUnitDay | NSCalendarUnitHour |
NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar *calendar = [[ NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [calendar components: allUnits
fromDate: [ NSDate date ] ];
[ weekdayComponents setHour: weekdayComponents.hour + 1 ];
[ weekdayComponents setMinute: 0 ];
[ weekdayComponents setSecond: 0 ];
NSDate *nextTime = [ calendar dateFromComponents: weekdayComponents ];
refreshTimer = [[ NSTimer alloc ] initWithFireDate: nextTime
interval: 0.0
target: self
selector: #selector( doRefresh )
userInfo: nil repeats: NO ];
[[NSRunLoop currentRunLoop] addTimer: refreshTimer forMode: NSDefaultRunLoopMode];
Of course, substitute "doRefresh" with your class's desired method
try to create the calendar object once and make the allUnits a static for efficiency.
adding one to hour component works just fine, no need for a midnight test (link)

Related

How to call a method every x seconds in Objective-C using NSTimer?

I am using Objective-C, Xcode 4.5.1 and working on an app for the iPhone.
I have a method A in which I want to call another method B to do a series of calculations every x seconds. In method A I start playing an audio file. Method B will monitor the audio every x seconds for the duration of the audio file.
I have found NSTimer as a potential solution, but am having a hard time getting it to work/understanding it.
I simply want to call Method B every x seconds and run its calculations, but NSTimer requires me to provide several things of which I'm not sure what I'm supposed to tell it.
[NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)
target:(id) select:(SEL) userInfo:(id) repeats:(BOOL)];
It is my understanding that at NSTimeInterval I provide the interval at which I want NSTimer to operate. But, how do I tell it to run Method B?
I have looked at example code, and am currently under the impression that I provide the method at the 'select:'. But, what do I write at the 'target:'? Why would I need a target? I tried entering 'self', but Xcode tells me:
Use of undeclared identifier 'self'
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
select:#selector(targetMethod:myVolumeMonitor()) userInfo:nil repeats:YES];
So, I figure 'self' is supposed to be a pointer to an object, but where do I want to point to?
Below is a simplification of my code:
MethodA()
{
//Start playing an audio file.
//NSTimer calling Method B, as long the audio file is playing, every x seconds.
}
MethodB()
{
//Do calculations.
}
I would be grateful if somebody could provide me with some answers/point me in the right direction! (:
Target is the recipient of the message named in select.
In Objective-C functions are not called. There are rather messages sent to objects. The Object internally refers to its symbol table and determines which of its methods is being called. That is a selector. Your selector is #selector(MethodB).
(BTW: you should start method names with lower case. "methodB" would be more appropriate here.)
This leads to the question: how to determine the object to which the message is sent? That is the target. In your case, it is simply self.
BTW: In this case the selector is expected to return void and accept an id, which is the id of the NSTimer object itself. That will come handy if you want the timer to stop firing based on some conditions according to your program logic.
Most important: Your selector is then methodB: rather than methodB.
- (void) methodA
{
//Start playing an audio file.
//NSTimer calling Method B, as long the audio file is playing, every 5 seconds.
[NSTimer scheduledTimerWithTimeInterval:5.0f
target:self selector:#selector(methodB:) userInfo:nil repeats:YES];
}
- (void) methodB:(NSTimer *)timer
{
//Do calculations.
}
try this
NSTimer *aTimer = [NSTimer timerWithTimeInterval:(x) target:self selector:#selector(timerFired:) userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:aTimer forMode: NSDefaultRunLoopMode];
[popUpImageView release];
- (void)timerFired:(NSTimer*)theTimer
{
if(condition)
{
[theTimer isValid]; //recall the NSTimer
//implement your methods
}
else
{
[theTimer invalidate]; //stop the NSTimer
}
}
If you look at your code and compared to the one below
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
select:#selector(targetMethod:myVolumeMonitor()) userInfo:nil repeats:YES];
self means that you are invoking a method in same instance of your class, in your example the method is myVolumeMonitor
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:#selector(MethodB) userInfo:nil repeats:YES];
and you are good to go though
method be should look like this
- (void)MethodB:(NSTimer*)timer {
// do something
}
Well you are trying to call an normal C method, NSTimer can't to that.
The target is the an instance of the class on which to call the selector, this selector adn not select. The selector here is a SEL type which you can create with the #selector(METHOD_NAME) function.
For example this will call the handleTimer : ever 0.1 second: (For this example the AppDelegate is used):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//SNIP, some code to setup the windos.
[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:#selector(handleTimer:) userInfo:nil repeats:YES];
return YES;
}
- (void) handleTimer:(NSTimer *)timer {
// Hanlde the timed event.
}

How to use NSTimers as associative references?

I've tried the following:
- (void)setupTimer {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(doSomething) userInfo:nil repeats:YES];
objc_setAssociatedObject(self, &key, timer, OBJC_ASSOCIATION_RETAIN);
[timer invalidate];
}
- (void)doSomething { /* ... */ }
- (void)afterDoingSomething { [objc_getAssociatedObject(self, &key) invalidate]; }
Yet, the timer doesn't tick (I didn't expected it to do so; this code just didn't look much right to me) for some reason. Is there a way to make it... work?
You're invalidating the timer immediately after creating and scheduling it. Remove the [timer invalidate]; line in -setupTimer:
- (void)setupTimer {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(doSomething) userInfo:nil repeats:YES];
objc_setAssociatedObject(self, &key, timer, OBJC_ASSOCIATION_RETAIN);
}
From the documentation:
[invalidate] stops the receiver from ever firing again and requests
its removal from its run loop.
Am I correct in assuming that this code is in a category? Otherwise, I can't think of a good reason to make the timer an associated object instead of just using a regular instance variable for it.
You've must have mistaken invalidate and release.
objc_setAssociatedObject does release for you when you set next item.
I don't think it is a problem with setting a timer as an associative reference.
You are killing your timer before it actually start (invalidate does so).
Your - (void)doSomething method should have different signature: - (void)doSomething: (NSTimer*)theTimer.
You may be leaking memory, you should do objc_setAssociatedObject(self, &key, nil, OBJC_ASSOCIATION_RETAIN); in your afterDoingSomething.

Is it possible to change an NSTimer's userInfo?

I have an NSTimer that has an NSNumber in its userInfo
fireTimer = [NSTimer scheduledTimerWithTimeInterval:6.0
target:self
selector:#selector(fireTileAddingToColumn:)
userInfo:myNumber
repeats:YES];
After the NSTimer is created and has run a couple of times, I would like to be able to change the value of myNumber and have it reflect in fireTileAddingToColumn: I have not had any luck getting this to work. Does anyone have any suggestions?
You can always pass an object holding the userInfo to the timer:
#interface Holder
#property id data;
-(id) initWithData: (id) data;
#end
// implement it
Holder *holder = [[Holder alloc] initWithData:myNumber];
fireTimer = [NSTimer scheduledTimerWithTimeInterval:6.0 target:self
selector:#selector(fireTileAddingToColumn:) holder
repeats:YES];
[Holder setData: myNumber2];
and the data change will be reflected in the selector
You're best off creating a new timer. If the class doesn't provide an interface for changing that attribute, then you should consider it private and read-only.
It's not even possible in this case to do the usual end run around that, using KVC:
[timer setValue:newNumber forKey:#"userInfo"];
since NSTimer is not KVC-compliant for that key.
The userInfo property of an NSTimer isn't intended to be a general-purpose data storage facility. It's there so that you can have some context go along with your timer, so that the target of the timer can distinguish one timer from another if multiple timers invoke the same action.
Lazy people's mutable userInfo:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:6.0
target:self
selector:#selector(fireTileAddingToColumn:)
userInfo:#{#"mutable": [#{#"key": <value>} mutableCopy]
repeats:YES];
And to access it:
timer.userInfo[#"mutable"][#"key"] = <newValue>;

Objective C: Call variable from another method

I'm trying to access an NSTimer in a method called getTimer in another method.
- (NSTimer *)getTimer{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector: #selector(produceBricks) userInfo:nil repeats:YES];
return timer;
[timer release];
}
I'm trying to stop the timer in another method (a method that would pause the game) by using:
if ([getTimer.timer isValid]) {
[getTimer.timer invalidate];
}
I'm assuming this is not the correct syntax being it tells me getTimer is undeclared. How would I access the timer so I can stop it?
getTimer is a method, not an object, so you can't send messages to it or access properties. Rather, assuming that the method is in the same class as the one calling it, you would call it like this:
NSTimer *timer = [self getTimer];
if ([timer isValid]) [timer invalidate];
//...
Also, you're trying to release your timer in the getTimer method after the return statement. This code will never be executed (the method has already ended) - which is good in this case, because you shouldn't release the timer, it's already autoreleased. I'd recommend that you read something on Objective-C memory management and naming conventions.
Make the timer an instance variable instead of creating in within getTimer. Then it will be accessible anywhere within the class as follows:
in MyClass.h
NSTimer* timer;
I would implement a startTimer and stopTimer method.
- (void) startTimer {
timer = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector: #selector(produceBricks) userInfo:nil repeats:YES];
}
- (void) stopTimer {
if([timer isValid]) {
[timer invalidate];
}
}

Accessing Instance Variables from NSTimer selector

Firstly newbie question: What's the difference between a selector and a method?
Secondly newbie question (who would have thought): I need to loop some code based on instance variables and pause between loops until some condition (of course based on instance variables) is met. I've looked at sleep, I've looked at NSThread. In both discussions working through those options many asked why don't I use NSTimer, so here I am.
Ok so it's simple enough to get a method (selector? ) to fire on a schedule. Problem I have is that I don't know how to see instance variables I've set up outside the timer from within the code NSTimer fires. I need to see those variables from the NSTimer selector code as I 1) will be updating their values and 2) will set labels based on those values.
Here's some code that shows the concept… eventually I'd invalidate the timers based on myVariable too, however I've excluded that for code clarity.
MyClass *aMyClassInstance = [MyClass new];
[aMyClassInstance setMyVariable:0];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(doStuff) userInfo:nil repeats:YES];
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(doSomeOtherStuff) userInfo:nil repeats:YES];
- (void) doStuff {
[aMyClassInstance setMyVariable:11]; // don't actually have access to set aMyClassInstance.myVariable
[self updateSomeUILabel:[NSNumber numberWithInt:aMyClassInstance.myVariable]]; // don't actually have access to aMyClassInstance.myVariable
}
- (void) doSomeOtherStuff {
[aMyClassInstance setMyVariable:22]; // don't actually have access to set aMyClassInstance.myVariable
[self updateSomeUILabel:[NSNumber numberWithInt:aMyClassInstance.myVariable]]; // don't actually have access to aMyClassInstance.myVariable
}
- (void) updateSomeUILabel:(NSNumber *)arg{
int value = [arg intValue];
someUILabel.text = [NSString stringWithFormat:#"myVariable = %d", value]; // Updates the UI with new instance variable values
}
You can use the userInfo parameter to transmit arbitrary object. In this case, you pass aMyClassInstance as userInfo:
MyClass *aMyClassInstance = [MyClass new];
[aMyClassInstance setMyVariable:0];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(doStuff) userInfo:aMyClassInstance repeats:YES];
In the timer callback (which MUST takes a parameter), you get back the userInfo from the timer and cast it:
- (void) doStuff:(NSTimer *)timer {
MyClass *instance = (MyClass *)[timer userInfo];
[instance setMyVariable:11];
[self updateSomeUILabel:[NSNumber numberWithInt:instance.myVariable]];
}
The neat thing is that the timer retains the userInfo parameter.
One of your questions was asking about the difference between a selector and a method.
A selector “selects” the method to use from an object. Imagine you had some animal classes, say Dog, Cat, and Bird, all subclasses of Animal. They all implement a method called makeSound. Each class will have its own implementation of makeSound, otherwise all of the animals will sound the same. So, all animals have a different method for making a sound, but you get each animal to make its sound using the same selector. You are selecting the makeSound method of an animal, in other words.
You do have access to instance variables if you set the instance as the target of the timer like so:
[NSTimer scheduledTimerWithTimeInterval:1.0 target:aMyClassInstance selector:#selector(doStuff) userInfo:nil repeats:YES];
The instance (which you've referred to as aMyClassInstance) will be self.
Alternatively you can put aMyClassInstance and any other objects in the userInfo dictionary. You would do that like so:
NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
aMyClassInstance, #"a",
bMyClassInstance, #"b",
cMyClassInstance, #"c",
nil];
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(doStuff:) userInfo:userInfo repeats:YES];
Then, in the doStuff: selector, you can get them back out like so:
-(void) doStuff:(NSTimer*)timer;
{
MyClass* aMyClassInstance = [[timer userInfo] objectForKey:#"a"];
MyClass* bMyClassInstance = [[timer userInfo] objectForKey:#"b"];
MyClass* cMyClassInstance = [[timer userInfo] objectForKey:#"c"];
//do whatever you want here
}