如何在Swift中每5秒运行一个带参数的函数? [英] How do I run a function with a parameter every 5 seconds in Swift?

查看:120
本文介绍了如何在Swift中每5秒运行一个带参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每5秒执行一次以下功能。我已经看到了相关的问题的其他答案说,使用 NSTimer.scheduledTimerWithTimeInterval 但是只适用于没有任何参数的函数。

I want to execute the following function every 5 seconds. I have seen the other answers to related questions that say to use NSTimer.scheduledTimerWithTimeInterval but that only works for functions without any arguments.

函数:

func sayHello(name: String) {
    println("Hey \(name)!")
}

这是我试过的代码:

var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("sayHello(\(name))"), userInfo: nil, repeats: true)

但它崩溃了应用程序时出现错误:

But it crashes the app with the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[Jake.SwiftApp sayHello(jake)]: unrecognized
selector sent to instance 0x7fcd515640a0'

有一个输入参数?

推荐答案

问题是, NSTimer 即可,只需传递方法的名称即可。

The problem is, when you set up the selector for the NSTimer to fire, you have to pass just the name of the method.

现在,动态构建一个字符串并尝试指向一个名为的方法:

Right now, you're dynamically building a string and trying to point to a method called:

"sayHello(jake)"

这不存在。其实,在不能存在。

Which doesn't exist. In fact, in can't exist. This doesn't even make sense.

sayHello() fun会像这样,如果你添加它作为具有字符串的选择器:

The sayHello() fun would look like this if you're adding it as a selector with a string:

"sayHello:"

但是只是修复这仍然会有问题。 NSTimer 的目标可以取零个或一个参数。如果它有一个参数,它期望参数是 NSTimer 。当 NSTimer '触发并调用其目标时,它们将自身作为参数传递。

But just fixing this will still be problems. An NSTimer's target can take zero or one arguments. And if it does take an argument, it expects that argument to be an NSTimer. When NSTimer's fire and call their target, they pass themselves as a parameter.

设置我们的方法如下:

func sayHello(timer: NSTimer) {
    // do stuff
}

现在我们通过 Selector

And now we pass Selector("sayHello:") for our selector argument.

为了传入任何类型的参数,我们必须将它们打包到 NSTimer userInfo 属性,类型 AnyObject?。然后,在我们的定时器调用的方法中,我们可以访问此属性。

In order to pass any sort of arguments in, we have to package them into the NSTimer's userInfo property, which is of type AnyObject?. Then, within the method our timer calls, we can access this property.

class ExampleClass {
    var timer: NSTimer?

    var userName: String? {
        set {
            self.timer?.userInfo = newValue
        }
        get {
            return self.timer?.userInfo as? String
        }
    }

    func timerTick(timer: NSTimer) {
        if let userName = timer.userInfo as? String {
            self.sayHello(userName)
        }
    }

    func sayHello(userName: String) {
        println("Hello " + userName + "!")
    }

    func startTimer(#interval: NSTimeInterval = 5.0, userName: String? = nil) {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(interval, 
            target: self, 
            selector: Selector("timerTick:"), 
            userInfo: userName, 
            repeats: true
        )
    }
}

从这里,任何时候你想改变定时器的名称,你可以do:

From here, any time you want to change the name the timer is carrying around, you can just do:

self.userName = "Jake"

这篇关于如何在Swift中每5秒运行一个带参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆