【问题标题】:How to call a selector-based Timer method on a Swift struct?如何在 Swift 结构上调用基于选择器的 Timer 方法?
【发布时间】:2017-10-24 01:13:00
【问题描述】:

这很有趣:您似乎无法在 swift struct 上调用选择器消息!我的意思是:我有一个struct 并想在其上实现一个简单的Timer,使用带有selector: 参数的Timer.scheduledTimer 的变体。编译器告诉我,被调用的选择器方法需要一个objc 属性才能使该方法对Objective-C 调用序列可见,但是对于非类对象不支持(又是另一个有用的编译器消息!;-)。

我认为在我的特定情况下使用struct 是一种更好的方法,但我想我将不得不将其反向移植到class,除非有人有更好的主意...

【问题讨论】:

  • 这真的是不可能的。您甚至如何将结构作为目标传递?它会被复制......计时器是为引用类型制作的。如果绝对需要(可能不需要),您可以使用 CFTimer。
  • 我没有传递结构。我正在尝试将选择器样式的消息@on@ 称为结构。抱歉,如果不清楚。 (而且很可能不是。这是一个很难描述的问题,我不确定我对技术词汇的掌握是否完全胜任这项任务。一个人只能做自己能做的事,但是......)跨度>
  • 这很有趣。
  • 要调用选择器,您需要传递目标。因此,您也必须传递结构。但这只是原因之一,如果这永远行不通。
  • @hkatz 不,它只是行不通。将选择器与值类型一起使用是不可能的。选择器本质上与引用类型相关联,或者更具体地说,与 NSObject 后代相关联。

标签: swift


【解决方案1】:

我知道这是一个老问题,但正如其他人在 cmets 中指出的那样,这是不可能的,无论如何直接。

您可以通过将计时器逻辑隔离到struct 内的class 中来实现在structs 内创建Swift Timers。总体规划如下。

  1. Timer 逻辑隔离到class 中的struct
  2. 传递包含的struct(或struct 中的一些其他class 实例)作为回传计时器滴答的一种方式。
  3. 实例化逻辑class,并在需要时存储对它的引用。

请看下面的代码示例。

struct MyStruct{
    
    var timerLogic: TimerLogic!

    class TimerLogic{
        var structRef: MyStruct!
        var timer: Timer!

        init(_ structRef: MyStruct){
            self.structRef = structRef;
            self.timer = Timer.scheduledTimer(
                timeInterval: 2.0,
                target: self,
                selector: #selector(timerTicked),
                userInfo: nil,
                repeats: true)
        }

        func stopTimer(){
            self.timer?.invalidate()
            self.structRef = nil
        }

        @objc private func timerTicked(){
            self.structRef.timerTicked()
        }
    }

    func startTimer(){
        self.timerLogic = TimerLogic(self)
    }    

    func timerTicked(){
         print("Timer tick notified")

         // Stop at some point
         // timerLogic.stopTimer()
         // timerLogic = nil
    }
}

【讨论】:

  • 感谢您抽出宝贵时间跟进,尽管已经过去了相当长的一段时间。这是一个有趣的答案,并且教会了我一些我以前不知道的东西。
  • 这是一个不错的解决方案,但有一个例外。在func startTimer() 中,Xcode 对self.timerLogic 大喊大叫。这样就不行了。
  • mutating func startTimer() { self.timerLogic = TimerLogic(self) } 这应该会有所帮助
猜你喜欢
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多