Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

objective c - Passing parameters to the method called by a NSTimer

How can I pass a parameter to the method called by a NSTimer? My timer looks like this:

[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES];

and I want to be able to pass a string to the method updateBusLocation. Also, where am supposed to define the method updateBusLocation? In the same .m file that I create the timer?

EDIT:

Actually I am still having problems. I am getting the error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[MapKitDisplayViewController updateBusLocation]: unrecognized selector sent to instance 0x4623600'

Here is my code:

- (IBAction) showBus {

//do something

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateBusLocation) userInfo:txtFieldData repeats:YES];
[txtFieldData release];
 }


 - (void) updateBusLocation:(NSTimer*)theTimer
 {
      NSLog(@"timer method was called");
      NSString *txtFieldData = [[NSString alloc] initWithString:(NSString*)[theTimer userInfo]];
if(txtFieldData == busNum.text) {
    //do something else
    }
    }

EDIT #2: Never mind your example code works fine thanks for the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to define the method in the target. Since you set the target as 'self', then yes that same object needs to implement the method. But you could have set the target to anything else you wanted.

userInfo is a pointer that you can set to any object (or collection) you like and that will be passed to the target selector when the timer fires.

Hope that helps.

EDIT: ... Simple Example:

Set up the timer:

    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0 
                              target:self 
                              selector:@selector(handleTimer:) 
                              userInfo:@"someString" repeats:NO];

and implement the handler in the same class (assuming you're setting the target to 'self'):

- (void)handleTimer:(NSTimer*)theTimer {

   NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]);

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...