Clicky

iOS Dev Nugget 310 Weak Reference Wrapper Class

.

Need to run a code review on your codebase? Hire me

Sometimes it's useful to keep a list of weak references to objects, especially to reduce the maintenance work needed to track when they are destroyed if you had kept a strong reference to them instead.

class C {}

This wouldn't work since they keep a strong reference:

class Watcher {
    var objects = [C]()
}

So you can define a WeakRef wrapper class:

class WeakRef<T: AnyObject> {
    weak var object: T?
    init(object: T) {
        self.object = object
    }
}

And this will work as expected:

class Watcher {
    var objects = [WeakRef<C>]()
}

Have fun with it!

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues