clementino clementino - 2 years ago 98
Swift Question

Swift 2 - EXC_BAD_ACCES when switching tabs

I have a swift 2 app with 2 tabs. On both screens I perform a dataTaskWithUrl in the viewDidAppear, to get the data refreshed when the screen appears.
This results, if I keep switching fast between the tabs back and forth, sooner or later I become an EXC_BAD_ACCESS, I suppose because of memory issues. My questions are:

1) Is it generally a bad practice to perform expensive tasks (such as http operations) in viewDidAppear?

2) If yes, what would be the best-practice in swift to refresh the data with appropriate memory management when the screen appears?

Answer Source

To analize your EXC_BAD_ACCESS, check if there are any var not initialized with a default value, or mathematical operation with nil values that can be caused this crash, wrong operation with empty arrays...

  • ViewDidLoad: Basically this method is called whenever the view was loaded into memory. So for example, adding views, labels, buttons here; the view will never exist without those forms.

  • ViewWillAppear: UIViews creations is fairly expensive, and you should avoid as much as possible doing that on the ViewWillAppear method, because when this gets called, it means that the iPhone is already ready to show the UIView to the user, and anything heavy you do here will impact performance in a very visible manner (like animations being delayed, etc).

  • ViewDidAppear: the best location to start off new threads to things that would take a long time to execute, like for example doing a webservice call to get extra data for the form above.The good thing is that because the view already exists and is being displayed to the user, you can show a nice "Waiting" message to the user while you get the data.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download