将参数传递给 NSTimer 调用的方法

发布于 2024-09-28 13:40:52 字数 1014 浏览 1 评论 0原文

如何将参数传递给 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: 没关系,您的示例代码工作正常,感谢您的帮助。

How can I pass a parameter to the method called by a NSTimer? My timer looks like this:

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

and I want to be able to pass a string to the method updateBusLocation. Also, where am supposed to define the method updateBusLocation? In the same .m file that I create the timer?

EDIT:

Actually I am still having problems. I am getting the error message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[MapKitDisplayViewController updateBusLocation]: unrecognized selector sent to instance 0x4623600'

Here is my code:

- (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
    }
    }

EDIT #2:
Never mind your example code works fine thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

烟火散人牵绊 2024-10-05 13:40:52

您需要在目标中定义方法。既然您将目标设置为“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]);
 
}

You need to define the method in the target. Since you set the target as 'self', then yes that same object needs to implement the method. But you could have set the target to anything else you wanted.

userInfo is a pointer that you can set to any object (or collection) you like and that will be passed to the target selector when the timer fires.

EDIT: ... Simple Example:

Set up the timer:

    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0 
                              target:self 
                              selector:@selector(handleTimer:) 
                              userInfo:@"someString" repeats:NO];

and implement the handler in the same class (assuming you're setting the target to 'self'):

- (void)handleTimer:(NSTimer*)theTimer {
 
   NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]);
 
}
紙鸢 2024-10-05 13:40:52

您可以使用 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];
}

You can pass your arguments with userInfo:[NSDictionary dictionaryWithObjectsAndKeys:parameterObj1, @"keyOfParameter1"];

A simple example:

[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];
}
痴梦一场 2024-10-05 13:40:52

对于 Swift 这样做,

例如您想使用 NSTimer 发送 UILabel

override func viewDidLoad() {
    super.viewDidLoad()

    var MyLabel = UILabel()
    NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("callMethod:"), userInfo: MyLabel, repeats: false)
}


 func callMethod(timer:NSTimer){

    var MyLabel:UILabel = timer.userInfo as UILabel

}

For Swift do like this,

For example you wants to send UILabel with NSTimer

override func viewDidLoad() {
    super.viewDidLoad()

    var MyLabel = UILabel()
    NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("callMethod:"), userInfo: MyLabel, repeats: false)
}


 func callMethod(timer:NSTimer){

    var MyLabel:UILabel = timer.userInfo as UILabel

}
花开浅夏 2024-10-05 13:40:52

对于Swift 4.0

您可以拥有一个带有任何所需参数的函数,并使用“scheduledTimer”块来执行您需要重复的代码。

func someFunction(param1: Int, param2: String) {

    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
        print(param1)
        print(param2)
    }
}

完成后请小心调用 timer.invalidate(),以防止其连续运行。

For Swift 4.0:

You can have a function with any parameters you want and use the "scheduledTimer" block to execute the code you need to repeat.

func someFunction(param1: Int, param2: String) {

    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
        print(param1)
        print(param2)
    }
}

Be careful to call timer.invalidate() when you finish to prevent it from running continuously.

征﹌骨岁月お 2024-10-05 13:40:52

Swift 中使用字典文字传递参数NSTimer 调用的方法的其他示例:

override func viewDidLoad() {
    super.viewDidLoad()

    let dictionary: [String : AnyObject] = ["first element" : "Jordan",
                                            "second element" : Int(23)]

    NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0.41),
                                           target: self,
                                           selector: "foo:",
                                           userInfo: dictionary,
                                           repeats: false)
}

func foo(timer: NSTimer) {
        let dictionary: [String : AnyObject] = timer.userInfo! as! [String : AnyObject]
        let firstElement: String = dictionary["first element"] as! String
        let secondElement: Int = dictionary["second element"] as! Int
        print("\(firstElement) - \(secondElement)")
}

Additional example in Swift using Dictionary literal for passing parameters to the method called by NSTimer:

override func viewDidLoad() {
    super.viewDidLoad()

    let dictionary: [String : AnyObject] = ["first element" : "Jordan",
                                            "second element" : Int(23)]

    NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0.41),
                                           target: self,
                                           selector: "foo:",
                                           userInfo: dictionary,
                                           repeats: false)
}

func foo(timer: NSTimer) {
        let dictionary: [String : AnyObject] = timer.userInfo! as! [String : AnyObject]
        let firstElement: String = dictionary["first element"] as! String
        let secondElement: Int = dictionary["second element"] as! Int
        print("\(firstElement) - \(secondElement)")
}
千纸鹤 2024-10-05 13:40:52

不是问题的直接答案,但由于我在搜索时遇到了这个问题,并且我需要一些不同的东西,它可能会对某人有所帮助。我想在辅助类中调用一个函数,我需要传入 UIViewController ,而不是与 userinfo 一起传递它,这不允许我在其他地方手动调用该函数,我创建了另一个函数计时器会从那里调用并调用我感兴趣的函数。一个有帮助的解决方法。

Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats:true);

func timerFired() {

myFunction(controller: self)

}

Not a direct answer to the question but since i ran into this while searching and i needed something different it may help someone. I wanted to call a funciton in a helper class, that i needed to pass in the UIViewController, rather than passing it with the userinfo which would not allow me to call the function manually elsewhere i created another function which the timer would call and called the function that i was interested in from there. A workaround that helped.

Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats:true);

func timerFired() {

myFunction(controller: self)

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文