[英]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.