NSTimer calling the sayOuch:-method


#1

Hi,

I successfully got to the Callbacks-chapter, which means you guys did a hell of a job writing this book! :slight_smile: But now, I do have a question to which I haven’t found the answer here yet:

Why do we define and implement the method for sayOuch with an argument (NSTimer *)t?

With my very flimsy knowledge of Objective-C so far I was kind of wondering where I missed where we passed the argument to the method, but I guess we just don’t. So why can’t we change this:

into

- (void) sayOuch; and remove the colon in the NSTimer-object, so we get:

__unused NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:2.0 target:logger selector:@selector(sayOuch) userInfo:nil repeats:YES];

Doing this still lets the NSTimer-object fire and log “Ouch” to the debug screen every 2 seconds.


#2

When the timer calls the sayOuch: method, it supplies it self as an argument, so sayOuch: is the canonical version.

Yes, it will work if you use sayOuch (no colon) and ignore which timer sent the message.


#3

This might be a stupid question, but what exactly do you mean by that? Thanks :slight_smile:

Also thank you Panpata for the question. I was wondering about this as well.


#4

This might be a stupid question, but what exactly do you mean by that? Thanks :slight_smile:

Also thank you Panpata for the question. I was wondering about this as well.
[/quote]
In this context, Canonical means the orthodox (standard) way of specifying the selector is @selector (timerExpired:) (the method takes a single argument which should be NSTimer*)

- (void)timerExpired:(NSTimer *)timer
{
...
}

#5

Ah, thanks for clarifying.


#6

I still don’t get it. Hopefully someone can clarify me on this.
When the “sayOuch” method took an NSTimer argument I was confused whether I didn’t understand the meaning of “target” correctly, but after reading the Apple documents I guess I was understanding it the right way.

__unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:logger selector:@selector(sayOuch:) userInfo:nil repeats:YES];

This just means “Every 2.0 seconds later, have the timer send [logger sayOuch] message”. And “sayOuch” doesn’t actually take “timer” as an argument; hence the warning if you don’t prefix “__unused”. Or maybe it does take “timer” and then does nothing with it and throws it away. I just feel like Apple’s being dumb on this matter.


#7

The __unused notation is to let the compiler know that YOU intentionally are not using the variable timer after setting it.

With a repeating timer, you will need the NSTimer variable to invalidate the timer when you are finished with it so it can stop firing!

In code, an unused variable is a hole. Why assign something if you don’t use it? If you DO use Timer in the following code, __unused is not needed.