在ios中异步调用数据库

lea*_*010 1 asynchronous core-data uitableview ios4

我的iPAD应用程序上有4个UITableView.我使用一个函数在它们上加载数据,该函数loadData存在于所有4个TableViewController.m文件中,这些函数调用数据库.

所以,我会做这样的事情

[aView loadData];
[bView loadData];
[cView loadData];
[dView loadData];
Run Code Online (Sandbox Code Playgroud)

其中aView,bView,cView和dView是UITableView的视图控制器.

但是,数据库调用是同步发生的,因此只有在从[aView loadData]函数中检索数据之后,函数才会[bView loadData]被调用,依此类推.

这会影响我的表现.

我想知道是否有一种方法可以异步调用数据库/异步调用调用数据库的函数.

如果有人可以帮我解决这个问题会很棒.

Ali*_*are 9

您可以使用GCD:

-(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];
      });
   });
}
Run Code Online (Sandbox Code Playgroud)

然后,当您调用该loadList方法时,activityIndi​​cator将开始动画,并且数据的获取过程将异步启动在单独的队列中,但loadList方法将立即返回(不等待块dispatch_async完成执行,这就是什么dispatch_async是为了).

因此,您loadList对每个视图控制器中的4个实现的所有调用都将立即执行(触发异步提取数据但不等待检索数据).一旦数据库请求 - 在并行队列中执行 - 已经在你的一个loadList方法中完成,dispatch_sync(...)就会执行块末尾的行,要求主队列(主线程)执行一些代码来刷新UI并显示新加载的数据.