bub*_*ter 60 cocoa-touch objective-c selector nstimer
如何将参数传递给NSTimer调用的方法?我的计时器看起来像这样:
[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)
我希望能够将字符串传递给方法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
}
}
Run Code Online (Sandbox Code Playgroud)
编辑#2:没关系,您的示例代码可以正常工作,感谢您的帮助.
Fir*_*eer 99
您需要在目标中定义方法.由于您将目标设置为"self",然后是同一对象需要实现该方法.但你可以将目标设定为你想要的任何其他东西.
userInfo是一个指针,您可以将其设置为您喜欢的任何对象(或集合),并在计时器触发时将其传递给目标选择器.
希望有所帮助.
编辑:...简单示例:
设置计时器:
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(handleTimer:)
userInfo:@"someString" repeats:NO];
Run Code Online (Sandbox Code Playgroud)
并在同一个类中实现处理程序(假设您将目标设置为'self'):
- (void)handleTimer:(NSTimer*)theTimer {
NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]);
}
Run Code Online (Sandbox Code Playgroud)
Ole*_*nov 23
您可以使用userInfo传递参数:[NSDictionary dictionaryWithObjectsAndKeys:parameterObj1, @"keyOfParameter1"];
一个简单的例子:
[NSTimer scheduledTimerWithTimeInterval:3.0
target:self
selector:@selector(handleTimer:)
userInfo:@{@"parameter1": @9}
repeats:NO];
- (void)handleTimer:(NSTimer *)timer {
NSInteger parameter1 = [[[timer userInfo] objectForKey:@"parameter1"] integerValue];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39077 次 |
| 最近记录: |