1

In our application we have several UITableViews which have network-backed data sources which can take time to actually populate. Here's what typically happens:

  1. User triggers view.
  2. In viewDidLoad, the view's datasource is created.
  3. The model's -load method is called
  4. The model issues a network request to get some data ...
  5. Before the request finishes, the user backs out of the view.
  6. The view's ViewWillDisappear, ViewDidDisappear, ViewDidUnload, and dealloc methods are called.
  7. The request finishes. Unfortunately, all or part of the table view is gone, so havoc ensues.

So, our solution has been to properly "tear down" the data source and cancel any outstanding network requests so this doesn't happen. The questions I have are:

  1. What is the "proper" way to tear down a data source? Do you you just lose all references to it, and use the -dealloc to cancel outstanding network requests?

  2. Where SHOULD you tear it down? In ViewDidUnload? dealloc?

  3. The same two questions apply to the Model, actually: What's the right way to tear it down? And when?

Note that this doesn't only apply to network requests: We have another view which uses Geolocation, and sometimes by the time the Geolocation completion block is called, the view it's supposed to update is long gone.

Thanks!

P.S. Additional question:

  1. In the case of UITableView, is it possible the rows in the view are deallocated BEFORE the UITableView's -dealloc is called? If they are deallocated at, say, ViewWillDisappear time, and the request happens to finish after that, but BEFORE -dealloc, then if the request happens to try and update UITableView rows, havoc will ensue.

Does that make sense?

4

1 回答 1

1

Are you using Objective-c, C++, or Objective-C++? I ask because you are referring to methods with c++ syntax (::) instead of obj-c (-), and I am not good with the c++ side.

Usually you implement the -dealloc method if your object has work to do when it is deallocated (torn down). In there you would cancel network requests and release any low-level resources like file handles. This method will be called automatically by the obj-c runtime when there are no more references to the instance and it is ready to deallocate it - you should not call this method manually.

The generally accepted pattern is to nil out any strong references to your object when you're done with it and let the runtime handle deallocating it. If you follow that pattern everywhere (networking, file system access, GPS, etc) it's pretty easy to work with.

于 2013-09-04T15:55:24.323 回答