[英]objc_getAssociatedObject always returns nil
我正在尝试使用关联对象将属性添加到Timer
的扩展中,但函数objc_setAssociatedObject
始终返回nil
。
Timer是一个NSObject,因此应该可以使用。
码:
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)
}
}
}
任何想法为什么这不起作用?
更多代码:
@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
}
所以有些问题是我没有使用相同的计时器对象。 仍然存在一些问题:
static let repeatCounterAddress = "repeat_counter_address"
有时未初始化,并且具有空字符串值。
有时我获得相同的关联值,有时却没有。
请尝试以下操作(请注意“&”号):
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)
}
}
}
这样始终可以确保为key
参数的值提供相同的地址 。 如果仅使用字符串值,则每次调用objc_getAssociatedObject
或objc_setAssociatedObject
,其原始值可能会有所不同。
您可以使用以下代码进行检查:
func test(_ a: UnsafeRawPointer) {
print("\(a)")
}
let a = "abc"
test(a)
test(a)
test(a)
test(a)
此打印
0x00006040004427e0
0x00006040004427e0
0x0000608000052980
0x0000600000055c50
例如,不同的原始指针被解释为不同的关联对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.