asynchronous calls to database in ios

2020-07-29 03:36发布

问题:

I have 4 UITableView's on my iPAD application. I load the data on them using a function loadData ,which is there in all the 4 TableViewController.m files, which makes calls to the database.

So, I would be doing something like this

[aView loadData];
[bView loadData];
[cView loadData];
[dView loadData];

Where aView, bView, cView and dView are the view controllers of the UITableView's.

However, the database calls happen synchronously and hence only after the data is retrieved from the [aView loadData] function, does the [bView loadData] function get called and so on.

This affects my performance.

I would like to know if there is a way I can asynchronously make calls to the database/ asynchronously make calls to functions which calls database.

It would be great if someone could help me out with this.

回答1:

You can use GCD for this:

-(void)loadList
{
   // You ma do some UI stuff
   [self.activityIndicator startAnimating]; // for example if you have an UIActivityIndicator to show while loading

   // Then dispatch the fetching of the data from database on a separate/paralle queue asynchronously (non-blocking)
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

      // this is executed on the concurrent (parallel) queue, asynchronously
      ... do your database requests, fill the model with the data

      // then update your UI content.
      // *Important*: Updating the UI must *always* be done on the main thread/queue!
      dispatch_sync(dispatch_get_main_queue(), ^{
          [self.activityIndicator stopAnimating]; // for example
          [self.tableView reloadData];
      });
   });
}

Then when you will call the loadList method, the activityIndicator will start animate, and the fetching process of your data will be started on a separate queue asynchronously, but the loadList method will return immediately (not waiting for the block in dispatch_async to finish executing, that's what dispatch_async is for).

So all your call to your 4 loadList implementations in each of your viewcontrollers will execute immediately, (triggering the fetching of your data asynchronously but not waiting for the data to be retrieved). Once the database requests -- that was executing in a parallel queue -- have finished in one of your loadList method, the dispatch_sync(...) line at the end of the block is executed, asking the main queue (main thread) to execute some code to refresh the UI and display the newly-loaded data.