Skip to content

Commit

Permalink
[0.0.3] Use NSMapTable to prevent from retain cycle
Browse files Browse the repository at this point in the history
  • Loading branch information
Shial committed Jun 13, 2017
1 parent 1c2ad2e commit a0fc079
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
2 changes: 1 addition & 1 deletion SCountLabel.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "SCountLabel"
s.version = "0.0.2"
s.version = "0.0.3"
s.summary = "Swift counting label."
s.description = <<-DESC
SCountLabel is an easy way to make your UIKit label count from one value to another!
Expand Down
17 changes: 8 additions & 9 deletions Sources/SCountLabel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import Foundation
import UIKit

extension UILabel {
func count(to: String, interval: TimeInterval = 0.2, format: [String]? = nil) {
Expand All @@ -15,7 +16,7 @@ extension UILabel {

func count(from: String, to: String, interval: TimeInterval = 0.05, format: [String]? = nil) {
struct Counter {
static var timer: [UILabel : Timer] = [:]
static var timer: NSMapTable<UILabel,Timer> = NSMapTable(keyOptions: NSPointerFunctions.Options.weakMemory, valueOptions: NSPointerFunctions.Options.strongMemory)
static func numbers(_ text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: "[\\-\\+]?[0-9]*(\\.[0-9]+)?")
Expand All @@ -42,8 +43,8 @@ extension UILabel {
}
}
}
Counter.timer[self]?.invalidate()
Counter.timer.removeValue(forKey: self)
Counter.timer.object(forKey: self)?.invalidate()
Counter.timer.removeObject(forKey: self)
text = from
let fromValues = Counter.numbers(from)
let toValues = Counter.numbers(to)
Expand All @@ -53,7 +54,7 @@ extension UILabel {
return
}
var round: Double = 1
Counter.timer[self] = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) {[weak self] timer in
Counter.timer.setObject(Timer.scheduledTimer(withTimeInterval: interval, repeats: true) {[weak self] timer in
var fromString = from
var shouldInvalidate = true
for i in 0..<numbersCount {
Expand All @@ -66,14 +67,12 @@ extension UILabel {
}
if shouldInvalidate {
self?.text = to
if let strongSelf = self {
Counter.timer[strongSelf]?.invalidate()
Counter.timer.removeValue(forKey: strongSelf)
}
Counter.timer.object(forKey: self)?.invalidate()
Counter.timer.removeObject(forKey: self)
} else {
self?.text = fromString
round = round + 1
}
}
}, forKey: self)
}
}

0 comments on commit a0fc079

Please sign in to comment.