How to retain lazy instance in cross ref objects

53 Views Asked by At

Given two classes which reference each other and one of the refs is weak, how do I retain it when initialising locally? This is the structure of the code:

class Generator {
    weak var machine: Machine!
    
    public init(for machine: Machine) {
        self.machine = machine
    }
    
    func start() {
        // ... code to start the generator
    }
    
    func generate() {
        machine.didGenerate(value: 1)
    }
}


class Machine {
    public lazy var generator: Generator = Generator(for: self)
    
    func start() {
        generator.start()
    }
    
    func didGenerate(value: Float) {
        // Use the value here
    }
}

The following usage works (example given in MacOS environment):

let machine = Machine()

func viewDidLoad {
    machine.start()
}

However this is not working:

func viewDidLoad {
    let machine = Machine()
    machine.start()
}

The machine reference in the Generator class is not retained. How can I retain it?

Tried to use unowned instead of weak, but not working too.

0

There are 0 best solutions below