Jawap Jawap - 1 year ago 80
iOS Question

How to instantiate an object that depends on self in the init function?

I understand that all properties need to be defined before calling

. But what if the initialization of a property depends on
? In my case I need to initialize an object that has a delegate, which I need to set to
. What is the best way to do this?

class MyClass : NSObject {
var centralManager : CBCentralManager
override init() {
centralManager = CBCentralManager(delegate: self, queue: nil)

This is wrong, because
is not initialized before
. But I can't change the order either, because then I would be using

Answer Source

The problem

Let's say CBCentralManager is defined as follow

protocol CBCentralManagerDelegate { }

class CBCentralManager {
    init(delegate: CBCentralManagerDelegate, queue: Any?) {

The solution

This is how you should define your class

class MyClass: CBCentralManagerDelegate {
    lazy var centralManager: CBCentralManager = {
        [unowned self] in CBCentralManager(delegate: self, queue: nil)

How does it work?

As you can see I am using a lazy property to populate the centralManager property.

The lazy property has an associated closure that is executed the first time the lazy property is read.

Since you can read the lazy property only after the current object has been initialised, everything will work fine.

Where's NSObject?

As you can see I removed the inheritance of MyClass from NSObject. Unless you have a very good reason to inherit from NSObject well... don't do it :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download