ios - 来自父类(super class)的 NSTimer 调用函数

标签 ios swift nstimer

假设我有一个用作计时器的类 Timer。

我希望所有其他可以像计时器一样工作的类都具有 Timer 类型的属性。

问题是:Timer 类使用了 NSTimer 属性,我不知道如何在其中关联来自外部 Timer 的函数。

例如:类A有属性B,即Timer。 scheduledTimerWithTimerInterval 如何调用 A 的某个函数?

这是计时器:

import UIKit
class Timer{

    var interval: NSTimeInterval!
    var counting: Bool = false
    var numberOfTouches: Int = 0
    private var timer: NSTimer = NSTimer()

    init(interval: CGFloat){
        self.interval = NSTimeInterval(interval)
        self.counting = false
    }

    func Start(function: String) {
        if(self.counting){
            self.numberOfTouches += 1
            self.timer.invalidate()
            self.timer = NSTimer.scheduledTimerWithTimeInterval(self.interval, target: self, selector: Selector(function), userInfo: nil, repeats: false)
        }
        else{
            self.counting = true
            self.numberOfTouches = 1
        }
    }

    func Stop(){
        if(!self.counting){
            self.counting = false
        }
    }
}

这是 View Controller :

import UIKit

class ViewController: UIViewController {

    var timer: Timer = Timer(interval: 1.0)

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func Trigger(sender: AnyObject) {
        //yes, this doesn't call t() from the ViewController
        timer.Start("self.t")

    }

    func t(){
        label.text = String(timer.numberOfTouches)
    }

    @IBOutlet weak var label: UILabel!

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

最后,这个计时器试图做的是:

  • 当我按下按钮时,它开始计数并将触摸次数设置为 1;
  • 如果我在之前触摸后不到 1 秒再次按下它,它会重新启动 1 秒计时器并将触摸增加 1;
  • 1 秒后没有任何触摸,它应该从 ViewController 调用 t() 以将标签设置为最后的触摸次数。

我应该使用什么方法来解决这个问题?

谢谢!

PS:一开始是Selector("Stop")

最佳答案

这不是 "self.t",您提供对象作为目标。选择器类似于 "ViewController.t""t"。您还需要更改 Start 以获取目标对象。

移至 Xcode 7.3.1 并尽可能使用新的选择器语法——它将进行类型检查。

关于ios - 来自父类(super class)的 NSTimer 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37421966/

相关文章:

iOS后台模式和NStimer

ios - NSTimer 中的 UserInfo 没有传递正确的信息 - Swift

ios - 苹果的Accelerate vDSP:如何从FFT获取复数向量的参数

ios - 是什么造成了不同

ios - NSMutableURLRequest 和 "request body stream exhausted"错误

android - iOS 应用签名和所有权

ios - UIPageControl 不滑动

ios - 以编程方式创建约束 - 2 个框

ios - Swift - scheduledTimer 秒表小时部分不工作

iphone - Xcode 4.2 首选项 "Support Wirelessly Connected Devices"有什么作用?