I'd like to set n
number of associated objects to an object in Swift
My understanding is the usual pattern for the UnsafeRawPointer
reference is like this...
static var reference = "someRef"
public func add(to myObject: AnyObject) {
let adding = ThingToAdd()
objc_setAssociatedObject(myObject, &reference, adding, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
but this wouldn't work for n
number of calls to add(to:)
Similarly, the below code works fine if I only call it once per myObject
.. However, if I add another associated object in the same way... it replaces the first ThingToAdd
with the second. Building a unique string inline does not work. On the simulator it's fine but on a device it's not.
public func add(to myObject: AnyObject) {
let adding = ThingToAdd()
var reference = "objectref\(UUID().uuidString)".replacingOccurrences(of: "-", with: "")
objc_setAssociatedObject(myObject, reference, adding, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
I understand that this is incorrect, however I don't know how to create n
number of UnsafeRawPointers
in order to store the associated objects with unique references.
Any help / explanation would be greatly appreciated.