Reputation: 2543
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
Reputation: 59536
Let's say CBCentralManager
is defined as follow
protocol CBCentralManagerDelegate { }
class CBCentralManager {
init(delegate: CBCentralManagerDelegate, queue: Any?) {
}
}
This is how you should define your class
class MyClass: CBCentralManagerDelegate {
lazy var centralManager: CBCentralManager = {
[unowned self] in CBCentralManager(delegate: self, queue: nil)
}()
}
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
fromNSObject
. Unless you have a very good reason to inherit fromNSObject
well... don't do it :)
Upvotes: 2