I'm trying to add properties to a extension to Timer
using associated objects, but the function objc_setAssociatedObject
always returns nil
.
Timer is a NSObject so this should work.
Code:
extension Timer {
private struct AssociatedKeys {
static var counterAddress = "counter_address"
}
public var repeatCounter: Int {
get {
return objc_getAssociatedObject(self, AssociatedKeys.counterAddress) as? Int ?? 0
}
set {
objc_setAssociatedObject(self,
AssociatedKeys.counterAddress,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Any ideas why is this not working?
more code:
@nonobjc public class func new(every interval: TimeInterval, _ block: @escaping (Timer) -> Void) -> Timer {
var timer: Timer!
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
print("timer: \(timer.numberOfRepeats), : \(timer.repeatCounter), : \(timer)")
if timer.numberOfRepeats > 0 {
if timer.repeatCounter > timer.numberOfRepeats {
timer.invalidate()
return
} else {
timer.repeatCounter += 1
}
}
block(timer)
}
return timer
}
So some of the problem was that I wasn't using the same timer object. There are still some issues:
static let repeatCounterAddress = "repeat_counter_address"
sometimes is not initialised and has an empty string value.Sometimes I get the same associated value and sometime not.