Overview
What’s use of Unmanaged in swift?
There are certain situations where we need low level lib in our project to communicate with swift code. Also, swift’s ARC memory management requires compiler to manage each object reference. Once the pointer is passed to C Lib, it can’t manage object reference. So we must have to manually manage it. Unmanage provide function to get object reference to swift compiler. Unmanaged wraps a reference to an object.
Topics
From Swift to C
There are two methods to carry out this.
- Using Unmanaged.passRetained(obj) will perform an unmanaged reference with an unbalanced retain. This grants ownership on whatever C API you’re passing the pointer to. It must be balanced with a release it, otherwise object will leak.
let objPtr = Unmanaged.passRetained(obj).toOpaque() FunctionCall(objPtr)
- Using Unmanaged.passUnretained(obj) will leave the object’s retain count unchanged. This does not grant any ownership on the C API. If object dealloc then app may crash as C internally retain object in any other process.
let objPtr = Unmanaged.passUnretained(obj).toOpaque() FunctionCall(objPtr)
Here, objPtr is UnsafeMutableRawPointer which is swift’s equivalent to C’s void *
From C to Swift
To retrieve a reference from C into Swift code, we need to create an Unmanaged value from the raw pointer, then take a reference from it
- Using takeRetainedValue will do an unbalanced release, also will balance an unbalanced retain previously performed with passRetained, or by C code which confers ownership on your code.
let obj = Unmanaged<ClassName>.fromOpaque(objPtr).takeRetainedValue() obj.method()
- Using takeUnretainedValue will obtain the object reference without performing any retain or release.
let obj = Unmanaged<ClassName>.fromOpaque(objPtr).takeUnretainedValue() obj.method()
Communicate with low level C function in swift.