1

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,

Community
  • 1
  • 1
Tom Major
  • 283
  • 1
  • 12
  • tldr; The key itself isn't unique to the instance, but the dictionary that the key is stored into is. – dgatwood Jan 30 '17 at 18:41
  • according to the answer from Nikolai Ruhe - http://stackoverflow.com/a/41830581/4206370 - it's not necessary to use really unique keys, because the instance pointer will be used (in objc_***AssociatedObject) as well for forming a unique key. So this will answer my question. – Tom Major Feb 26 '17 at 18:04
  • You misread the other response slightly. The instance isn't used in forming the key, but rather the key and the associated value are stored **inside** the instance. You can basically think of associated objects as storing a key and value into a hidden NSDictionary ivar inside NSObject. (It isn't literally an NSDictionary, but a more precise explanation would require a complete understanding of the Objective-C runtime, and that's a close enough approximation of the way it behaves for most purposes.) – dgatwood Feb 27 '17 at 02:29
  • @dgatwood Thanks for pointing this out. – Tom Major Mar 01 '17 at 14:12

0 Answers0