每个 1.2.0

Each 1.2.0

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布最新发布2017 年 3 月
SwiftSwift 版本3.0
SPM支持 SPM

dalu93 维护。



Each 1.2.0

Each

优雅Swift 应用的界面

BuddyBuild

Each 是一个用 Swift 编写的 NSTimer 桥接库。

特点

  • [x] 完全可配置的计时器
  • [x] 支持毫秒、秒、分钟和小时的间隔时间
  • [x] 全部可扩展
  • [x] 比NSTimer对象更易读且易于使用

需求

  • iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.0+
  • Swift 3.0+

用法

创建新的计时器实例

let timer = Each(1).seconds     // Can be .milliseconds, .seconds, .minute, .hours  

执行操作

timer.perform {
    // Do your operations
    // This closure has to return a NextStep value
    // Return .continue if you want to leave the timer active, otherwise
    // return .stop to invalidate it
}

如果您希望将内存管理决策交给 Each 类,可以使用简单的 perform(on: _) 方法。它需要一个 AnyObject 实例。

timer.perform(on: self) {
    // Do your operations
    // This closure has to return a NextStep value
    // Return .continue if you want to leave the timer active, otherwise
    // return .stop to invalidate it
}

手动停止计时器

timer.stop()    // This stops immediately the timer

重新启动计时器

您只能在停止计时器后重新启动计时器。此方法使用相同的执行闭包重新启动计时器。

timer.restart()

泄露

不幸的是,接口不能帮助您处理定时器可能创建的内存泄露。在这种情况下,提供了两种解决方案

解决方案 1

请参考 用法 部分,使用 perform(on: _) 方法。请注意,使用此方法时,当 owner 被销毁时,不会立即销毁 timer。它将在 timer 触发下一次并检查 owner 实例是否仍然有效时销毁。

解决方案 2

如果您不想声明一个持有所引用的Each属性,请在方法作用域中创建一个普通的Each计时器,在每个owner实例为nil时返回.stop/true

Each(1).seconds.perform { [weak self] in
    guard let _ = self else { return .stop }

    print("timer called")
    return .continue
}

90%的闭包会以某种方式调用self,所以这并不那么糟糕

解决方案3

如果第一个解决方案不足以解决问题,您可以声明一个持有所引用的Each属性,并在释放owner时调用stop()函数

final class ViewController: UIViewController {
    private let _timer = Each(1).seconds

    deinit {
        _timer.stop()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        _timer.perform {
            // do something and return. you can check here if the `self` instance is nil as for workaround #1
        }
    }
}

许可证

Each遵循MIT许可证发布。请参阅LICENSE文件以获取详细信息。