如何将参数传递给NSTimer调用的方法?我的计时器如下所示:

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

我希望能够将字符串传递给updateBusLocation方法.另外,我应该在哪里定义updateBusLocation方法?同样的.我创建计时器的m文件?

EDIT:

其实我还是有问题.我收到了错误信息:

由于未捕获的异常"NSInvalidArgumentException"而终止应用程序,原因:"*-[MapKitDisplayViewController updateBusLocation]:未识别的 Select 器已发送到实例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是一个指针,您可以将其设置为任何喜欢的对象(或集合),并在计时器启动时将其传递给目标 Select 器.

希望有帮助.

EDIT: ... Simple Example:

设置计时器:

    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]);

}

Objective-c相关问答推荐

跨平台 iPhone/Android 代码共享

如何在没有 Interface Builder 的情况下创建 Cocoa 接口?

如何使用 NSFileManager 删除目录及其内容

iOS UIImageView 缩小图像在 iPad 2 上产生锯齿图像

在objective-c中isa是什么意思?

iOS 应用 Display Recorder 如何在不使用私有 API 的情况下录制屏幕?

当前时间是 HH:MM:SS am/pm 格式吗?

带有 IB_DESIGNABLE 的 UIButton 会引发运行时属性警告,并且不会在 Interface Builder 中呈现

如何使用整数值作为键在 NSMutableDictionary 中设置值?

dispatch_semaphore_dispose 上的 EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

判断用户是否在连续的 UISlider 上完成滑动?

如何四舍五入浮点值?

首次提交应用内购买以供审核

Core Data使用原始数据类型的标量属性复选框

Core Text在iOS中计算字母框架

-[MyClassName copyWithZone:] 无法识别的 Select 器发送到实例

如何为 iPhone 应用程序创建多个主题/皮肤?

如何在 Xcode 7 中启用_BITCODE?

如何在 NSUserDefaults 中保存 NSMutablearray

哪个是正确的,nil 或 NULL,来标记没有 Objective-C 块?