0

I'm trying to light up a bunch of vibrant UIButton subclass instances by calling the flash() method given by:

func flash(delay: TimeInterval = 0.0) {
    DispatchQueue.main.asyncAfter(deadline: .now() + delay)  { [weak self] in
        guard let strongSelf = self else { return }
        let flashView = UIView(frame: strongSelf.bounds)
        strongSelf.insertSubview(flashView, at: 0)
        flashView.backgroundColor = strongSelf.color
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { flashView.removeFromSuperview() }
    }
}

Using this function I can for-loop through an array of buttons triggering a flash effect that lasts for 0.1 seconds with the flashing caused by the vibrancy layer altering the flashView instance behind it.

Does this function have any drawbacks by calling DispatchQueue.main.asyncAfter within a call to DispatchQueue.main.asyncAfter?

ajrlewis
  • 2,968
  • 3
  • 33
  • 67

2 Answers2

0

No , it doesn't as here no need for [weak self] as this GCD ( Grand Central Dispatch ) doesn't cause retain cycles

DispatchQueue.main.asyncAfter(deadline: .now() + delay)  { /*[weak self] in */

Check last section Here

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

I don't see any problems with nested calls to DispatchQueue.main.asyncAfter(). However, each call to your flash function is creating and adding a new subview to your view. That will create an ever-increasing stack of subviews to accumulate as the animation runs (which will cause your memory usage to grow slowly until you free the button views.

You should refactor your flashing views to have an instance variable to a single subview and change it's color to cause a flash rather than adding a new one each time.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks. Does the line ` DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { flashView.removeFromSuperview() }` not remove the instance of `flashView` after 0.1 seconds? So the subviews won't continually add to the button? – ajrlewis Dec 24 '18 at 15:00
  • Oh, sorry. I missed that bit. Indeed it will remove the subview. – Duncan C Dec 24 '18 at 16:57