我的ViewController中到我的自定义Cocoapod类的侦听器-Swift

时间:2018-11-30 14:02:12

标签: swift delegates cocoapods listener protocols

我已经建立了自己的Cocoapod,该Cocoapod目前每秒触发updateCounting()函数。我的最终目标是使用protocol,以便可以在每次updateCounting()触发时触发的视图控制器类中使用某种委托方法。

我的公共Cocoapod文件当前如下所示:

public class Service: NSObject {
    var timer = Timer()
    public static let shared = Service()

    public func scheduledTimerWithTimeInterval(){
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true)
    }

    @objc func updateCounting(){
        NSLog("counting..")
    }
}

我的VC类当前看起来像:

import UIKit
import JacquardToolkit

class ViewController: UIViewController {
    override func viewDidLoad() {
         super.viewDidLoad()
         Service.shared.scheduledTimerWithTimeInterval()
    }
}

我最初的想法是像这样向我的Service类添加一个协议:

public protocol ServiceDelegate: NSObjectProtocol {
    func timerFired()
}

public class Service: NSObject, ServiceDelegate {

    var timer = Timer()
    public static let shared = Service()

    public func scheduledTimerWithTimeInterval(){
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats: true)
    }

    @objc public func timerFired() {
        NSLog("timerfired")
    }

}

到目前为止,我已经陷入困境,但是我实质上是想在VC类中建立一个侦听器,以便每次timerFired()updateCounting()触发时,我都可以在VC类中检测到它并采取相应的措施。任何帮助表示赞赏:)

1 个答案:

答案 0 :(得分:0)

您几乎已经实现了Delegate模式,但是您可能需要做一些更小的修改,例如下面的代码:

class ViewController: UIViewController, ServiceDelegate {
override func viewDidLoad() {
    super.viewDidLoad()
    Service.shared.delegate = self
    Service.shared.scheduledTimerWithTimeInterval()
}

func timerFired() {

    NSLog("timerfired")
}
}
public protocol ServiceDelegate: NSObjectProtocol {
    func timerFired()
}

public class Service: NSObject {


var timer = Timer()
public static let shared = Service()
weak var delegate:ServiceDelegate?

public func scheduledTimerWithTimeInterval(){
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats: true)
}

@objc public func timerFired() {
    NSLog("timerfired")
    delegate?.timerFired()
}

}