gpt4 book ai didi

ios - 无法识别的选择器发送到实例 - Swift 3

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:08 25 4
gpt4 key购买 nike

我根据这段代码创建了一个类:https://gist.github.com/etartakovsky/06b8c9894458a3ff1b14

当我尝试实例化类并调用 tick 方法时,出现“无法识别的选择器已发送到实例”错误。我一遍又一遍地检查了代码,但不明白为什么会这样,欢迎任何建议:

秒表类来源:

import Foundation
import QuartzCore

class StopWatch: NSObject{

private var displayLink: CADisplayLink!
private let formatter = DateFormatter()

var callback: (() -> Void)?
var elapsedTime: CFTimeInterval!

override init() {
super.init()

self.displayLink = CADisplayLink(target: self, selector: "tick:")
displayLink.isPaused = true
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)

self.elapsedTime = 0.0

formatter.dateFormat = "mm:ss,SS"
}
convenience init(withCallback callback: @escaping () -> Void) {
self.init()
self.callback = callback
}
deinit {
displayLink.invalidate()
}

func tick(sender: CADisplayLink) {
elapsedTime = elapsedTime + displayLink.duration
callback?()
}

func start() {
displayLink.isPaused = false
}

func stop() {
displayLink.isPaused = true
}

func reset() {
displayLink.isPaused = true
elapsedTime = 0.0
callback?()
}

func elapsedTimeAsString() -> String {
return formatter.string(from: Date(timeIntervalSinceReferenceDate:elapsedTime))
}

}

这是 ViewController 代码:

import UIKit

class ActivityViewController: UIViewController {

let stopwatch = StopWatch()

@IBOutlet weak var elapsedTimeLabel: UILabel!

func tick() {
elapsedTimeLabel.text = stopwatch.elapsedTimeAsString()
}

override func viewDidLoad() {

super.viewDidLoad()
tick()
stopwatch.callback = self.tick
stopwatch.start()


// Do any additional setup after loading the view.
}

}

最佳答案

在 Swift 3 中使用 #selector 语法

self.displayLink = CADisplayLink(target: self, selector: #selector(tick))

在 Swift 4 中,你还必须在操作的开头插入 @objc

@objc func tick(...

关于ios - 无法识别的选择器发送到实例 - Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47237270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com