0

Normally when using objc_setAssociatedObject, the recommended practice is to create a static variable, then use its address (via the '&' prefix) as the key.

However, we have a case where we need to associate an arbitrary number of classes with one 'owner' class, and as such, each needs its own unique key. My thought was to use the actual address of the class instance for that purpose.

The issue I'm running into is I can only seem to get the address as an Int, but the function expects an UnsafeRawPointer and I haven't found any code that lets me initialize, or convert to one from an int.

So again, while I can get the address as an int with this code...

func addressOf<T: AnyObject>(_ object: T) -> Int {
    return unsafeBitCast(object, to:Int.self)
} 

let classA = MyClass()
let classB = classA

let a = addressOf(classA)
let b = addressOf(classB)

// Result: a == b

I can't get a/b as an UnsafeRawPointer. Is this even possible?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • 1
    Did you see the comment at your previous question https://stackoverflow.com/q/59785859/1187415? – Martin R Jan 17 '20 at 11:30
  • I can't catch the goal... what to what you're going to associate? You name *classA* in `let classA = MyClass()`, but result of `MyClass()` is a reference to object of type `MyClass`. `UnsafeRawPointer` in `objc_setAssociatedObject` is needed for *key*, which is just a key, that is why it is usually used as static (similarly as used constant string keys for dictionaries)... So I'm lost... – Asperi Jan 17 '20 at 16:10
  • There could be 50 of these classes added as associated objects so I need 50 distinct keys. That's why I wanted to use the address of the instance data itself (as opposed to the variable's address which would be the same, thus it would overwrite the object) as the key. – Mark A. Donohoe Jan 17 '20 at 16:21

0 Answers0