Junior — Middle
How can you create a data structure that maintains weak references to objects?
sobes.tech AI
Answer from AI
To create a data structure that holds weak references to objects in iOS (Swift/Objective-C), the class NSMapTable or NSHashTable with weak reference options is used.
Weak references allow objects to be deallocated from memory if there are no strong references to them, preventing memory leaks.
Example in Swift with NSMapTable:
let mapTable = NSMapTable<NSString, AnyObject>.weakToWeakObjects()
let key = "key" as NSString
var object: NSObject? = NSObject()
mapTable.setObject(object, forKey: key)
object = nil // now the object can be deallocated from memory
if let value = mapTable.object(forKey: key) {
print("Object exists")
} else {
print("Object was deallocated")
}
You can also use a Weak wrapper — a wrapper with a weak reference inside, if you need your own data structure.
Thus, to store weak references, NSMapTable with weak-to-weak or weak-to-strong configuration is used, depending on the task.