3

I'm porting one part of my objective-c framework where I had my custom MyNotificationCenter class for observing purposes.

The class had a property of type NSArray with all observables which are interested in notifications.

In objective-c, an array retains its elements, and that is unneeded because observer may not exist anymore at the point when center tries to notify him, and you don't want to have retain cycle.

Therefore I was using this block of code which kept all the items in the array without retaining them:

_observers = CFBridgingRelease(CFArrayCreateMutable(NULL, 0, NULL)); 

I know Swift is a different beast, however is there such concept in Swift?

Centurion
  • 14,106
  • 31
  • 105
  • 197
  • 2
    Possible duplicate of [How do I declare an array of weak references in Swift?](http://stackoverflow.com/questions/24127587/how-do-i-declare-an-array-of-weak-references-in-swift) – holex Oct 18 '16 at 15:00

2 Answers2

3

Yes, an Array object in Swift retains its elements. From the Apple Documentation:

Swift’s Array type is bridged to Foundation’s NSArray class.

so it has the same behavior of NSArray.

Reading your ObjectiveC code, what you want to achieve is to have an NSArray-like class that doesn't retain elements. This can be also achieved in another way using NSHashTable:

NSHashTable *array = [NSHashTable weakObjectsHashTable];

The NSHashTable has almost the same interface as the normal NSSet (NSHashTable is modeled after NSSet), so you should be able to replace your NSArray value with NSHashTable value with small changes.

Marco Pace
  • 3,820
  • 19
  • 38
  • `NSHashTable` is more like an `NSSet` rather than an `NSArray`; I think it is just a typo only. – holex Oct 18 '16 at 15:13
2

Yes, Swift arrays do retain their elements

Let's define a simple class

class Foo {
    init() {
        print("Hello!")
    }
    deinit {
        print("Goodbye...")
    }
}

And now let's try this code

var list = [Foo()]
print(1)
list.removeAll()

This is the output

Hello!
1
Goodbye...

As you can see the Foo object is retained in memory until it is removed from the array.

Possible solution in Swift

You could create your own WeakArray struct in Swift where each element is wrapped into a class with a weak reference to the element. The class object is then inserted into the array.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148