Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a weak reference set in Swift

NSSet holds strong references to its objects so the Objective C solution was to use NSHashTable.weakObjectsHashTable() a la

NSHashTable* mySet = [NSHashTable weakObjectsHashTable];
[mySet addObject:anyOldObject];
[mySet count]; //returns 1
[mySet containsObject:anyOldObject]; //returns true

in swift however this does not seem to work

var mySet = NSHashTable.weakObjectsHashTable()
mySet.addObject(anyOldObject)
mySet.count //returns 1
mySet.containsObject(anyOldObject) //returns false

What am I missing? Or is this a bug?

like image 315
Hammer Avatar asked Jul 25 '14 18:07

Hammer


People also ask

What is a weak reference in Swift?

Weak References are one solution to retain cycles in Swift. A weak reference does not increment or decrement the reference count of an object. Since weak references do not increment the reference count of an object, a weak reference can be nil. This is because the object could be deallocated while the weak reference is pointing to it.

What is an unowned reference in Swift?

Unowned References in Swift Another solution to retain cycles is an unowned reference. Like a weak reference, an unowned reference does not increment or decrement the reference count of an object. However, unlike a weak reference, the program guarantees to the Swift compiler that an unowned reference will not be nil when it is accessed.

What is a strong reference cycle in Swift?

In Swift, a closure captures its context. This means it strongly references anything referred to inside of it. If you have a closure that belongs to a class, and you call self inside that closure, you create a strong reference cycle. The closure strongly references to self. And self (the class) strongly references to the closure.

Why do we use weak self in Swift?

In Swift, [weak self] prevents closures from causing memory leaks in your application. This is because when you use [weak self], you tell the compiler to create a weak reference to self. In other words, the ARC can release self from memory when necessary.


1 Answers

On Xcode6b5 and using a string as the anyOldObject, I am able to see a return true happening. There were some bugs in 6b4 that prevented optional values from being returned in the interpreter which meant they were being aggressively cleaned up - it might be a problem like this which had the same effect here. It's worth re-trying to see if you have the same behaviour in the latest beta.

like image 159
AlBlue Avatar answered Oct 21 '22 15:10

AlBlue