【发布时间】:2019-11-20 01:32:48
【问题描述】:
问题总结:
如果您有一个 Swift 类,它在其初始化程序中将选择器作为参数,您如何手动“触发/调用”该选择器?
完整问题:
考虑以下在 Swift 中创建自定义计时器的尝试:
let TIME_INTERVAL = 0.1
class ValueAnimator : NSObject {
private var timer = Timer()
private let maxRep: Int
private var currentRepIndex: Int = 0
private var selector: Selector
init(durationInSeconds: Int, selector: Selector) {
print("VALUEANIMATOR INIT")
self.maxRep = Int(Double(durationInSeconds) / TIME_INTERVAL)
self.selector = selector
}
func start() {
timer = Timer.scheduledTimer(timeInterval: TIME_INTERVAL, target: self, selector: (#selector(timerCallback)), userInfo: nil, repeats: true)
}
@objc func timerCallback() {
currentRepIndex += 1
perform(selector) // <-------- this line causes crash, "unrecognized selector sent to instance 0x600001740030"
print ("VA timer called!, rep: \(currentRepIndex)")
if currentRepIndex == maxRep {
timer.invalidate()
print("VA timer invalidated")
}
}
}
这个“ValueAnimator”的用法与普通的 Timer/NSTimer 类似,因为您将“选择器”作为参数传递,并且每次 ValueAnimator 触发时都会调用该选择器:
[在父类中]:
// { ...
let valueAnimatorTest = ValueAnimator(durationInSeconds: 10, selector: #selector(self.temp))
valueAnimatorTest.start()
}
@objc func temp() {
print("temp VA callback works!") // this doesn't happen :(
}
我正在尝试实现同样的事情,据我所知,这行:
perform(selector)
应该在父类中触发选择器,但我收到错误:“无法识别的选择器发送到实例 0x600001740030”
我在这里有点过头了。我试过用谷歌搜索错误,但似乎每个人都在谈论如何使用父方的选择器(如何使用 Timer.scheduledTimer() 等),但我已经知道如何成功地做到这一点。
我还尝试了对代码的各种调整(更改公共/私有、变量范围和 performSelector() 函数的不同形式)...但无法找出使选择器触发的正确方法...或者我犯的不相关的错误,如果有的话。
感谢您的帮助。
【问题讨论】:
-
ValueAnimator 本身是否超出范围并被删除?
标签: ios swift timer callback selector