Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should self be weak in UIView.animate when there is a delay and in collection view perform batch updates?

Tags:

ios

swift

weak

In general I'm aware that we do not need to make self weak when using UIView.animate() because the block isn't held strongly but is there an argument for using weak in the following bit of code due to the delay? Why would someone say there could be?

UIView.animate(withDuration: 0.1, animations: {
  self.performAction()
}

In the following example why do we need to use weak self/not need to use weak self...?

collectionView.performBatchUpdates({
    self.collectionView.reloadData()
    ...
})
like image 523
jeh Avatar asked Jun 13 '17 10:06

jeh


1 Answers

Background :

Blocks/Closures are nothing more than a reference counted objects in Heap Memory. When you create a block and hold the strong reference to block/closure you declared the reference count of the block gets incremented by 1.

Obviously this means that block will not be released even after its execution from the memory, until all the Classes strongly holding the reference to the block release their strong hold.

Now keeping that in mind, if you pass a strong self to block, because the variables used inside the block are kept alive till the block finishes its execution (Context capturing which is the main difference between function and blocks) self will not be released until the block itself is released.

Now thats a deadLock :) Your self holds a strong reference to the block object and block object intern holds the strong reference to self. Now both will wait for each other to release and end up never releasing each other.

Answer to your question :

As you pointed out if you are not strongly holding the reference of UIView.animate block, there is no compelling reason for you to pass weak self so is the case for collectionView batch update.

In your case

collectionView.performBatchUpdates({
    self.collection.reloadData()
    ...
})

I believe collection is collectionView, if its a IBOutlet you must have observed that its been declared as weak object. So your code must have looked more like

collectionView.performBatchUpdates({
    self.collection?.reloadData()
    ...
})

Hope it helps

like image 135
Sandeep Bhandari Avatar answered Nov 12 '22 17:11

Sandeep Bhandari