Accessing Instance Variables from NSTimer selector - objective-c

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
}

Related

Passing an argument with an NSTimer and from a regular call to the same method

I need to pass an integer to my method startEvent:. The method is a timer's action method. I've read about how to pass data with userInfo, however I don't understand how to do that so I can still call the method as I'd normally do.
How do I pass integers from an NSTimer and from a regular call to the same method?
[NSTimer scheduledTimerWithTimeInterval:0.032f target:self selector:#selector(startEvent:) userInfo:nil repeats:NO];
[self startEvent: 0];
-(void)startEvent:(int) event {
// ...
}
Use a pass-through for the timer's action method:
- (void)startEventFromTimer:(NSTimer *)tim
{
[self startEvent:[[tim userInfo] intValue]];
}
Where your timer was created with an NSNumber for its user info object.
[NSTimer scheduledTimerWithTimeInterval:0.032f
target:self
selector:#selector(startEventFromTimer:)
userInfo:#(theIntYouWantToPass)
repeats:NO];
You are starting from a fundamental misunderstanding. Your method cannot be the timers action method unless it conforms to the documented signature.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html
(void)timerFireMethod:(NSTimer *)timer
The only opportunity you have to pass additional information in is via the userinfo object, as Josh Caswells answer demonstrates.

Display NSArray at specific intervals

I have an NSArray that I would like to display each object at a specific time interval, for example:
NSArray *array = [NSArray arrayWithObjects:#"foo",#"bar",#"baz",nil];
and output it:
for (object in array) {
NSLog(#"%#", object);
// wait 3 seconds then show next object
}
so it should do this:
foo
... wait three seconds
bar
... wait three seconds
baz
... wait three seconds
repeat
how can i do this?
The simplest approach would be to use Blocks...
You can explore how to do this with a Blocks using third party categories such as :
https://github.com/zwaldowski/BlocksKit
As for a solution without blocks:
#property (nonatomic, strong) NSArray *myArray;
#property (nonatomic) NSInteger iteration;
- (void)awakeFromNib //Or equivalent method called when you want to start scheduling..
{
self.myArray = [NSArray arrayWithObjects:#"foo",#"bar",#"baz",nil];
self.iteration = 0;
[NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:#selector(fireEvent)
userInfo:nil
repeats:YES]; //Will Fire every 3 seconds...
}
-(void)fireEvent
{
NSLog(#"%#", [self.myArray objectAtIndex:self.iteration]);
self.iteration++;
if (self.iteration>=self.myArray.count) self.iteration=0;
}
If you with to invalidate the timer after all elements from the array are shown. Do the following :
-(void)awakeFromNib //Or equivalent method called when you want to start scheduling..
{
self.myArray = [NSArray arrayWithObjects:#"foo",#"bar",#"baz",nil];
self.iteration = 0;
[NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:#selector(fireEvent:)
userInfo:nil
repeats:YES]; //Will Fire every 3 seconds...
}
-(void)fireEvent:(NSTimer*)timer
{
NSLog(#">>>> %#", [self.myArray objectAtIndex:self.iteration]);
self.iteration++;
if (self.iteration>=self.myArray.count) {
self.iteration=0;
[timer invalidate];
}
}
NOTE: The latter code only adds a ':' to the #selector(fireEvent:). And reads the NSTimer reference in the fireEvent as a parameter.
Depending on the surrounding context, you might be able to do what you want by letting an NSRunLoop run for 3 seconds. Alternatively, and perhaps a bit safer and saner, you could use an NSTimer to run an action every 3 seconds.
I'd originally suggested breaking up the loop, logging the first element, then perform the same action on the rest of the array after a 3-second delay, using either something like performSelector:withObject:afterDelay: or dispatch_after, but as danielbeard pointed out, NSTimer provides a much more straight-forward way to cancel the action (cancellation is possible with the other methods, but requires planning and manual work).
Edit: If I were going to do this with an NSTimer, I'd probably use this NSTimer+Blocks category and do something like (untested code):
__block NSUInteger index = 0;
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:3.0 block:^{
NSLog(#"%#", array[index]);
index++;
if (index >= [array count]) {
[timer invalidate];
}
} repeats:YES];

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.
}

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>;

How do I use NSTimer?

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)