Swift Unmanaged

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.

From Swift to C

There are two methods to carry out this.

  1. 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.

  1. 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.

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

  1. 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.

  1. Using takeUnretainedValue will obtain the object reference without performing any retain or release.

Communicate with low level C function in swift.

mm

Chirag Daslaniya Sr. iOS Developer

Chirag Daslaniya is a passionate Mobile Application Developer, especially for iOS at Yudiz Solutions Pvt. Ltd. – a leading iPhone App Development company. He is zealous about making easy-to-use and user-friendly applications using simple yet striking interfaces.

Comments are closed.

Top