简体   繁体   中英

Do Swift arrays retain their elements?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM