iOS sending parameter to selector using NSTimers

2019-08-03 09:47发布

问题:

Is there a way to send a parameter to the selector via a NSTimer ?

myTimer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(removeTheNote:) userInfo:nil repeats:NO];

      - (void)removeTheNote:(NSString*)note
    {
        NSLog(@"Note %@ ----------- REMOVED!",note);
    }

I know that using :

myTimer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(removeTheNote:myNote) userInfo:nil repeats:NO];

doesn't work, so I am asking, is there a way to do this?

回答1:

You can use the userInfo parameter for that:

myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(removeTheNote:) userInfo:myNote repeats:NO];

But you will have to modify removeTheNote as follows:

- (void)removeTheNote:(NSTimer *)timer
{
    NSString *note = timer.userInfo;
    NSLog(@"%@", note);
}