Jawap
Jawap

Reputation: 2543

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

I understand that all properties need to be defined before calling super.init(). But what if the initialization of a property depends on self? In my case I need to initialize an object that has a delegate, which I need to set to self. What is the best way to do this?

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

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

Upvotes: 3

Views: 366

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59536

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 :)

Upvotes: 2

Related Questions