Junior — Middle
How can you implement adding an object to an array so that it does not lead to an increase in strong references to it?
sobes.tech AI
Answer from AI
To add an object to an array without increasing strong references to it, you can use weak references. In iOS, this is often done with NSPointerArray with weak options or by wrapping objects in weak containers.
Example with NSPointerArray:
let weakArray = NSPointerArray.weakObjects()
class MyObject {}
var obj = MyObject()
weakArray.addPointer(Unmanaged.passUnretained(obj).toOpaque())
Now, weakArray holds a weak reference to obj, which does not increase its retain count. When obj is deallocated, the pointer in the array automatically becomes nil.
If you use a regular array [MyObject], adding an object to it will increase its retain count, which is not suitable for this task.