Fast lazy variable and didReceiveMemoryWarning

I want to load a nib file lazily, in Swift, so I do

lazy var MyNib: UINib?  = {
    let uiNib:UINib = MyClass.nib();
    return uiNib;


I realize this is only called once.

So, if I get makeReceiveMemoryWarning, tests seem to show that setting it to nil does not affect the fact that it is not reinitialized when accessed at a later date, as can be done with C objects.

The big issue is with NSFetchedResultControllers, as I might actually want to unload a load of data and then reload it later.

How can this be done in Swift?



source to share

1 answer

As a workaround, you can use your own backup property that comes natively nil

and implement a computed property around it. A computed property implements both getter and setter, with the getter checking if the bake property is null, initializing it if necessary.

private var _nib: UINib?

var uiNib: UINib {
    get {
        if _nib == nil {
            _nib = MyTestClass.nib();
        return _nib!
    set { _nib = nil }


This way, you can set the property nil

as many times as you like, making sure that the next time you access it in read mode, it will be reinitialized again.

Note that this implementation is not thread safe - but most likely it will only be used from the main thread.



All Articles