简体   繁体   English

如果有延迟并且在集合视图中执行批量更新,UIView.animate中的自身应该是弱吗?

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

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? 一般来说,我知道在使用UIView.animate()时我们不需要自我弱,因为块没有强烈保持,但是由于延迟,是否存在在下面的代码中使用弱的参数? 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()
    ...
})

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. 当您创建一个块并保持对块/闭包的强引用时,您声明该块的引用计数增加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. 正如您所指出的,如果您没有强烈持有UIView.animate块的引用,则没有令人信服的理由让您传递弱自我,因此collectionView批量更新的情况也是如此。

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. 我相信collection是collectionView,如果它是一个IBOutlet,你必须观察它被声明为弱对象。 So your code must have looked more like 所以你的代码必须看起来更像

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

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM