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 a strong references of its elements. Even if this behaviour 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 and example to understand why we should use it.

Why Weak References?

Let’s use, as 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

classView{}

classDrawer{

private letviews:[View]

init(views:[View]){

self.views=views

}

funcdraw(){

// draw something in views

}

}

classViewManager{

private varviewA:View?=View()

private varviewB:View?=View()

private vardrawer:Drawer

init(){

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

}

funcdestroyViews(){

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 a NSPointerArray.

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

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

1

2

3

4

5

6

7

8

classMyClass{}

vararray=NSPointerArray.weakObjects()

letobj=MyClass()

letpointer=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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

extensionNSPointerArray{

funcaddObject(_object:AnyObject?){

guard letstrongObject=objectelse{return}

letpointer=Unmanaged.passUnretained(strongObject).toOpaque()

addPointer(pointer)

}

funcinsertObject(_object:AnyObject?,at index:Int){

guard index<count,letstrongObject=objectelse{return}

letpointer=Unmanaged.passUnretained(strongObject).toOpaque()

insertPointer(pointer,at:index)

}

funcreplaceObject(at index:Int,withObject object:AnyObject?){

guard index<count,letstrongObject=objectelse{return}

letpointer=Unmanaged.passUnretained(strongObject).toOpaque()

replacePointer(at:index,withPointer:pointer)

}

funcobject(at index:Int)->AnyObject?{

guard index<count,letpointer=self.pointer(at:index)else{returnnil}

returnUnmanaged<AnyObject>.fromOpaque(pointer).takeUnretainedValue()

}

funcremoveObject(at index:Int){

guardindex<countelse{return}

removePointer(at:index)

}

}

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

1

2

3

4

5

vararray=NSPointerArray.weakObjects()

letobj=MyClass()

array.addObject(obj)

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

1

2

array.compact()

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

classView{}

classDrawer{

private letviews:NSPointerArray

init(views:NSPointerArray){

self.views=views

}

funcdraw(){

// draw something in views

}

}

classViewManager{

private varviewA:View?=View()

private varviewB:View?=View()

private vardrawer:Drawer

init(){

letarray=NSPointerArray.weakObjects()

array.addObject(viewA)

array.addObject(viewB)

self.drawer=Drawer(views:array)

}

funcdestroyViews(){

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:

1

2

protocolMyProtocol: class{}

If you want to play with NSPointerArray, I suggest you to avoid the Playground since you may have odd behaviours 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:

1

2

3

4

ifletfirstObject=array.object(at:0)as?MyClass{// Cast to MyClass

print("The first object is a MyClass")

}

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:

1

2

3

4

5

6

7

8

9

classWeakRef<T>whereT: AnyObject{

private(set)weakvarvalue:T?

init(value:T?){

self.value=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:

1

2

3

4

5

6

vararray=[WeakRef<MyClass>]()

letobj=MyClass()

letweakObj=WeakRef(value:obj)

array.append(weakObj)

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:

1

2

3

4

funccompact(){

array=array.filter{$0.value!=nil}

}

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

classView{}

classDrawer{

private letviews:[WeakRef<View>]

init(views:[WeakRef<View>]){

self.views=views

}

funcdraw(){

// draw something in views

}

}

classViewManager{

private varviewA:View?=View()

private varviewB:View?=View()

private vardrawer:Drawer

init(){

vararray=[WeakRef<View>]()

array.append(WeakRef<View>(value:viewA))

array.append(WeakRef<View>(value:viewB))

self.drawer=Drawer(views:array)

}

funcdestroyViews(){

viewA=nil

viewB=nil

}

}

A cleaner version using the typealias:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

typealiasWeakRefView=WeakRef<View>

classView{}

classDrawer{

private letviews:[WeakRefView]

init(views:[WeakRefView]){

self.views=views

}

funcdraw(){

// draw something in views

}

}

classViewManager{

private varviewA:View?=View()

private varviewB:View?=View()

private vardrawer:Drawer

init(){

vararray=[WeakRefView]()

array.append(WeakRefView(value:viewA))

array.append(WeakRefView(value:viewB))

self.drawer=Drawer(views:array)

}

funcdestroyViews(){

viewA=nil

viewB=nil

}

}

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. ¯\_(ツ)_/¯

Share this:

Related

Marco Santarossa

Hi there, I'm Marco and I'm an Italian developer. I moved to London in 2016 to work at Sky as iOS developer.
I've been an iOS Developer since 2011 and I sometimes write embarrassing PHP/JS code.
I'm keen to learn new things and I spend most of my spare time learning as self-taught.
When I don't develop, I like watching MMA fights and cooking Italian food.

8 Comments

Hi Marco, Nice article and very good written! Good job! But I really wonder where we could use it? In example above it is enough just add some drain() function in Drawer class and call it in destroyViews() method.

Yep the case #2 is right. I used the weak reference because if for some reasons I have to destroy the object “observer” I’m able to do it without caring of removing it with removeObserver. I’ve forgotten too many times to call the removeObserver of NSNotificationCenter 😅

I may be wrong, but flatMap is used to transform an array of element A to an array of element B removing the element nil. It means that with that code we transform an array of WeakRef to an array of MyClass not-nil, we can test it with it:

1

2

3

letarray2=array.flatMap{$0.value}

print(type(of:array2))

We can use this higher-order function also to filter the nil elements, but it works just with $0 since you are going to transform the array of element A to an array of element A not-nil.

We can use array.flatMap { $0 } to remove all nil WeakRef, but we cannot use it to remove all WeakRef with value to nil.