1

Is it possible to re-access object from it's ObjectIdentifier

ex:

let controller = UIViewController() //assume controller has strong ref so it's not going to deallocate instantly 
let id = ObjectIdentifier(controller)

so how to access controller with it's ObjectIdentifier

SPatel
  • 4,768
  • 4
  • 32
  • 51

2 Answers2

2

No, this is not possible.

ObjectIdentifier is declared in the open sourced Swift Standard Library, so we can look at a snippet of it's implementation from GitHub (I have stripped out non-essential code and comments):

@frozen
public struct ObjectIdentifier {

  internal let _value: Builtin.RawPointer

  public init(_ x: AnyObject) {
    self._value = Builtin.bridgeToRawPointer(x)
  }

  public init(_ x: Any.Type) {
    self._value = unsafeBitCast(x, to: Builtin.RawPointer.self)
  }
}

We see that the implementation's stored _value is marked internal, so you will not be able to access it from code defined in other modules at all. In addition, only a pointer to the object is stored, meaning there is no 'direct' access to the object anyway.

Your best option is to just keep around the object, and create an ObjectIdentifier as and when you need it. Alternatively, you can re-implement ObjectIdentifier in your own module to be able to access the underlying object/pointer.

Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45
1

ok i get it.

let controller = UIViewController()

let id = ObjectIdentifier(controller)
let bitptr = UInt(bitPattern: id)

let _viewController:UIViewController? = unsafeBitCast(bitptr, to: UIViewController.self)
SPatel
  • 4,768
  • 4
  • 32
  • 51
  • Well, I had no idea that was possible! For what it's worth though, I wouldn't recommend using such a type-unsafe way of retrieving the original value. – Bradley Mackey Jan 23 '20 at 12:09
  • 3
    Why go via ObjectIdentifier? If the intention is to (unsafely!!!) convert an instance pointer to an integer and back then `let id = unsafeBitCast(controller, to: Int.self)` and `let vc = unsafeBitCast(id, to: UIViewController.self)` would do the trick. But note that this bypasses the reference counting: If the view controller is deallocated in between then this will crash. With the `Unmanaged` api you can do such conversions *and* retain/release the reference count accordingly, see the link at my above comment. – Martin R Jan 23 '20 at 12:49