2

As a new developer I'm a little unsure about how much we should clean up after ourselves with Swift on iOS. There is a lot of different information as this also has changed a lot since the beginning of iOS.

So when we have static Views and use storyboard I get the idea that everything is cleaned for us and we don't have to do (nearly) anything.

But what about when I create my view dynamically based on user clicks? And what is the best approach for clearing up references in case it is necessary?

Right now I'm doing like I'd do in Android simply settings my global reference to nil before I make a new instance of a View etc. I've read this should be done like:

myView?.removeFromSuperview()
Warpzit
  • 27,966
  • 19
  • 103
  • 155
  • 1
    If your goal is clean-up, you shouldn't need to call `removeFromSuperview`. If your goal is changing the UI, call `removeFromSuperview` where appropriate. If you're using references & weak references correctly (as Apple does a pretty good job of), there is almost no "clean up" code that needs to be written in Swift. – nhgrif Jun 14 '16 at 12:35

2 Answers2

1

Even if you create a view dynamically, you don't have to call removeFromSuperview, because the view's reference to its super view is a weak one.

See this topic for more info.

Community
  • 1
  • 1
Code
  • 6,041
  • 4
  • 35
  • 75
1

Although automatic reference counting approach used by Swift is very different from garbage collection approach of Java, the feel to programmers is surprisingly similar. On one hand, you have to be conscious about a possibility of creating circular references in Swift, and insert weak references to avoid circularity. On the other hand, you can rely on having your resources released promptly after releasing the last reference, and use deinit method to deal with clean-up.

But what about when I create my view dynamically

Creating views dynamically and adding them to Cocoa's view hierarchy ensures that your views would be released when view hierarchy decides that it no longer needs them.

You have to be careful in situations when views are recycled by Cocoa, e.g. when you add views to table view cells or collection view cells. Since cells are recycled, you need to either (1) remove added views to avoid adding them again, or (2) check if the view has been added, and reuse what is already there.

One way to drop added views when cells are recycled is by implementing prepareForReuse method, and removing the added view there.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523