How can I deallocate all references elements from an array?

前端 未结 1 1779
执笔经年
执笔经年 2021-01-27 14:16

I\'m trying to create a retrying mechanism for our network calls. I have created 2 classes. One a retry Class and another a Manager in case I wanted I can cancel all classes.

相关标签:
1条回答
  • 2021-01-27 14:41

    Not sure if I can answer your question, but I will try with my best understanding :).

    Apple's Swift handbook on Automatic Reference Counting (ARC) covers your question very well.

    Usually you don't need to have an array of optionals,

    var retries = [Retry]() 
    ...
    retries.removeAll()
    

    will nicely remove all containing objects and delete the references to these objects. From your context presented above I do not understand why you need to declare an array of optionals. As you know Swift optionals under the hood are just a typed wrapper class Optional<Type>, which doesn't work around the memory allocation problem.

    How does array reference objects?

    The array will increase the contained objects' reference count by one, that is, a strong reference.

    To ensure the objects in the array to be deallocated, one must make their reference count equal zero. Removing them from the array will do the trick, if nothing else is referencing the contained objects.

    Beware of the reference cycle though. In your case, you should not hold reference to the retries array in Retry instance. Otherwise even if you set the retries array to nil, the array and its contained objects still have strong reference to each other, meaning their reference counts will never reduce to zero, causing memory leak.

    0 讨论(0)
提交回复
热议问题