Explanation for unique association key in a stored property in Swift

86 Views Asked by At

I am referring to a question about emulating stored properties in Swift, and the answer from jou:

How to have stored properties in Swift, the same way I had on Objective-C?

Currently I am using that answer to add custom properties to MPMediaItemCollection in the following way:

file: Extension.swift

private var xoAssociationKey1: UInt8 = 0
private var xoAssociationKey2: UInt8 = 0

extension MPMediaItemCollection {
    var customTag: UInt64? {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey1) as? UInt64
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKey1, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
    var customString: String? {
        get {
            return objc_getAssociatedObject(self, &xoAssociationKey2) as? String
        }
        set(newValue) {
            objc_setAssociatedObject(self, &xoAssociationKey2, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
}

jou writes:

The association key is a pointer that should be the unique for each association. For that, we create a private global variable and use it's memory address as the key with the & operator.

The thing I don't get, why is this a unique key for each instance of MPMediaItemCollection? Won't each instance on MPMediaItemCollection use the memory address of the same private global variable xoAssociationKey1/2 and be therefore not unique, which would spoil this design? Or did I miss something about Associated Objects, and xoAssociationKey1/2 does not have to be unique for each class instance?

Thanks,

0

There are 0 best solutions below