如何将参数传递给 NSTimer 调用的方法?我的计时器如下所示:
[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES];
并且我希望能够将字符串传递给方法 updateBusLocation。另外,应该在哪里定义方法 updateBusLocation?在我创建计时器的同一个 .m 文件中?
编辑:
其实我还是有问题。我收到错误消息:
由于未捕获的异常“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]);
}
https://stackoverflow.com/questions/4011297/
相关文章:
c++ - 我可以在同一个 Xcode 项目中拥有 Swift、Objective-C、C 和 C+
iPhone - dequeueReusableCellWithIdentifier 用法
") 运算符在 C 与 Objec">objective-c - 点 (".") 运算符和箭头 ("->") 运算符在 C 与 Objec
iphone - NSNumber 和 NSInteger 有什么区别?
objective-c - objective-c : convert a NSMutableStr
ios - 从 NSUserDefaults 字典 iOS 中删除所有键