Search code examples
swiftnsfetchedresultscontrollerlazy-initialization

Swift 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 understand this is only ever called once.

So, if I get a didReceiveMemoryWarning, tests seem to show that setting it to nil has no effect in that it is not re-initialized when accessed at a later date, as can be done with Objective C properties.

More of an issue is NSFetchedResultControllers in that I may genuinely may wish to unload a load of data and then reload at a later date.

How can this be achieved in Swift?

Thanks


Solution

  • As a workaround, you can use a backing private property which is initially nil, and implement a computed property around it. The computed property implements both getter and setter, with the getter checking whether the baking property is nil, initializing it if needed.

    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 to nil as many times as you want, being sure that the next time it is accessed in read mode it is reinitialized again.

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