如何将参数传递给 NSTimer 调用的方法?我的计时器看起来像这样:
[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES];
我希望能够将字符串传递给 updateBusLocation 方法。另外,应该在哪里定义 updateBusLocation 方法?在我创建计时器的同一个 .m 文件中?
EDIT:
其实我还是有问题。我收到错误消息:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“*-[MapKitDisplayViewController updateBusLocation]:无法识别的选择器发送到实例 0x4623600'
这是我的代码:
- (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
}
}
编辑#2:
没关系,您的示例代码工作正常,感谢您的帮助。
您需要在目标中定义方法。既然您将目标设置为“self”,那么是的,同一个对象需要实现该方法。但你可以将目标设定为你想要的任何其他目标。
userInfo 是一个指针,您可以将其设置为您喜欢的任何对象(或集合),并且在计时器触发时将其传递到目标选择器。
编辑:...简单的例子:
设置定时器:
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(handleTimer:)
userInfo:@"someString" repeats:NO];
并在同一个类中实现处理程序(假设您将目标设置为“self”):
- (void)handleTimer:(NSTimer*)theTimer {
NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)