DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Top Java Collection Interview Questions for 2021
  • The Developer's Guide to Collections: Queues
  • The Developer's Guide to Collections
  • Reversing an Array: An Exploration of Array Manipulation

Trending

  • Java Parallel GC Tuning
  • Unleashing the Power of Microservices With Spring Cloud
  • A Better Web3 Experience: Account Abstraction From Flow (Part 2)
  • Effective Tips for Debugging Complex Code in Java
  1. DZone
  2. Coding
  3. Languages
  4. Swift Arrays Holding Elements With Weak References

Swift Arrays Holding Elements With Weak References

This tutorial talks about when it's actually better to use weak references with arrays in Swift arrays for iOS development.

Marco Santarossa user avatar by
Marco Santarossa
·
Jul. 04, 17 · Tutorial
Like (5)
Save
Tweet
Share
7.79K Views

Join the DZone community and get the full member experience.

Join For Free

In iOS development, there are moments where you ask yourself: “To weak, or not to weak, that is the question.” Let’s see how “to weak” with the arrays.

Overview

In this article, I speak about memory management without explaining it since it would be beyond the goal of this article. The official documentation is a good starting point to learn this subject. Then, if you have other doubts, please leave a comment and I’ll reply as soon as possible.

Array is the most popular collection in Swift. By default, it maintains strong references of its elements. Even if this behavior is useful most of the time, you might have some scenarios where you would want to use weak references. For this reason, Apple provides an alternative to Array which maintains weak references of its elements: NSPointerArray.

Before looking at this class, let’s see an example to understand why we should use it.

Why Weak References?

Let’s use, as an example, a ViewManager class which has two properties of type View. In its constructor, we add these views in an array to inject inside Drawer—which uses this array to draw something inside the views. Finally, we have a method destroyViews to destroy the two Views:

class View { }

class Drawer {

    private let views: [View]

    init(views: [View]) {
        self.views = views
    }

    func draw() {
        // draw something in views
    }
}

class ViewManager {

    private var viewA: View? = View()
    private var viewB: View? = View()
    private var drawer: Drawer

    init() {
        self.drawer = Drawer(views: [viewA!, viewB!])
    }

    func destroyViews() {
        viewA = nil
        viewB = nil
    }
}

Unfortunately, destroyViews doesn’t destroy the two views because the array inside Drawer is maintaining a strong reference of the views. We can avoid this problem replacing the array with anNSPointerArray.

NSPointerArray

NSPointerArray is an alternative to Array with the main difference that it doesn’t store an object but its pointer (UnsafeMutableRawPointer).

This type of array can store the pointer maintaining either a weak or a strong reference depending on how it’s initialized. It provides two static methods to be initialized in different ways:

let strongRefarray = NSPointerArray.strongObjects() // Maintains strong references
let weakRefarray = NSPointerArray.weakObjects() // Maintains weak references

Since we want an array of weak references, we’ll use NSPointerArray.weakObjects().

Now, we can add a new object in this array:

class MyClass { }

var array = NSPointerArray.weakObjects()

let obj = MyClass()
let pointer = Unmanaged.passUnretained(obj).toOpaque()
array.addPointer(pointer)

Since using the pointer may be annoying, you can use this extension which I made to simplify the NSPointerArray:

extension NSPointerArray {
    func addObject(_ object: AnyObject?) {
        guard let strongObject = object else { return }

        let pointer = Unmanaged.passUnretained(strongObject).toOpaque()
        addPointer(pointer)
    }

    func insertObject(_ object: AnyObject?, at index: Int) {
        guard index < count, let strongObject = object else { return }

        let pointer = Unmanaged.passUnretained(strongObject).toOpaque()
        insertPointer(pointer, at: index)
    }

    func replaceObject(at index: Int, withObject object: AnyObject?) {
        guard index < count, let strongObject = object else { return }

        let pointer = Unmanaged.passUnretained(strongObject).toOpaque()
        replacePointer(at: index, withPointer: pointer)
    }

    func object(at index: Int) -> AnyObject? {
        guard index < count, let pointer = self.pointer(at: index) else { return nil }
        return Unmanaged<AnyObject>.fromOpaque(pointer).takeUnretainedValue()
    }

    func removeObject(at index: Int) {
        guard index < count else { return }

        removePointer(at: index)
    }
}

Thanks to this extension, you can replace the previous example with:

var array = NSPointerArray.weakObjects()

let obj = MyClass()
array.addObject(obj)

If you want to clean the array removing the objects with value nil, you can call the method compact():

array.compact()

At this point, we can refactor the example used in “Why Weak References?” with the following code:

class View { }

class Drawer {

    private let views: NSPointerArray

    init(views: NSPointerArray) {
        self.views = views
    }

    func draw() {
        // draw something in views
    }
}

class ViewManager {

    private var viewA: View? = View()
    private var viewB: View? = View()
    private var drawer: Drawer

    init() {
        let array = NSPointerArray.weakObjects()
        array.addObject(viewA)
        array.addObject(viewB)
        self.drawer = Drawer(views: array)
    }

    func destroyViews() {
        viewA = nil
        viewB = nil
    }
}

Note:

You may have noticed that NSPointerArray stores pointers of AnyObject only, it means that you can store just classes—so neither structs nor enums. You can store protocols if they have the keyword class:

protocol MyProtocol: class { }

If you want to play with NSPointerArray, I suggest you avoid the Playground since you may have odd behaviors with the retain count. A sample app would be better.

Alternatives

NSPointerArray is very useful to store objects maintaining weak references, but it has a problem: it’s not type-safe.

For “not type-safe”, I mean that the compiler is not able to infer the type of the objects inside NSPointerArray, since it uses pointers of objects AnyObject. For this reason, when you get an object from the array, you must cast it to your object type:

object(at:) comes from my NSPointerArray extension which I shown previously.

If we want to use a type-safe alternative we can’t use NSPointerArray anymore.

A possible workaround is creating a new class WeakRef with a generic weak property value:

private(set) exposes value in read-only mode, in this way no one can set its value from outside the class.

Then, we can create an array of WeakRef, where value is your MyClass object to store:

Now, we have an array type-safe which maintains a weak reference of your MyClass objects. The disadvantage of this approach is that we must add an extra layer in our code (WeakRef) to wrap the weak reference in a type-safe way.

If you want to clean the array removing the objects with value nil, you can write the following method:

filter returns a new array with the elements that satisfy the given predicate. You can find more details in the documentation.

Now, we can refactor the example used in “Why Weak References?” with the following code:

A cleaner version using the typealias:

Dictionary and Set

This article has the main focus on Array, if you need something similar to NSPointerArray for Dictionary you can have a look at NSMapTable, whereas for Set you can use NSHashTable.

If you want a type-safe Dictionary/Set, you can achieve it storing a WeakRef object.

Conclusion

I guess you are not going to use arrays with weak references very often, but it’s not an excuse not to know how to achieve it. In iOS development, the memory management is very important to avoid memory leaks, since iOS doesn’t have a garbage collector.

Element Data structure Object (computer science) Swift (programming language) Holding (law)

Published at DZone with permission of Marco Santarossa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Top Java Collection Interview Questions for 2021
  • The Developer's Guide to Collections: Queues
  • The Developer's Guide to Collections
  • Reversing an Array: An Exploration of Array Manipulation

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: