To have an associated object in Swift, you simply use a memory address as a handle, and then use the objc calls.
The usual example code you can google everywhere is:
var keyA:UInt8 = 0
var keyB:UInt8 = 0
extension UIViewController {
var aoAA: String? {
get { return objc_getAssociatedObject(self, &keyA) as? String }
set { objc_setAssociatedObject(self, &keyA, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
var aoBB: String? {
get { return objc_getAssociatedObject(self, &keyB) as? String }
set { objc_setAssociatedObject(self, &keyB, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
}
this works fine,
class Thing: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
aoAA = "this is a"
print("...... \(aoAA)")
aoBB = "this is b"
print("...... \(aoBB)")
aoAA = "changed A"
print("...... \(aoAA) \(aoBB)")
aoBB = "changed B"
print("...... \(aoAA) \(aoBB)")
aoAA = aoBB
print("...... \(aoAA) \(aoBB)")
}
But wait...
The handles, keyA and keyB, are global to the whole project.
When you use aoAA and aoBB in different UIViewController, how can it possibly be that aoAA and aoBB act as properties specific to that instance?
Surely there is only "one" aoAA everywhere in the project?
ie, aoAA is a global - just as the handle keyA is a global?
My testing seemed to show that they are independent variables, specific to different instances of different UIViewControllers, but that seems barmy.
How can each instance of aoAA
possibly be different - it's using the same global handle?