我正在编写一个从服务器获取数据的iOS应用。我有几个ViewControllers。我曾经在viewDidLoad方法下为该viewcontroller加载数据

-(void)ViewDidload
{
    [self loadData];
}


-(void)loadData
{
    //calling to webservice caller class
}


但这会降低应用程序的性能。在ViewController中加载数据的最佳方法是什么?对于网络服务调用,我有一个单独的类。在我的loadData方法中,我调用了Webservice调用类中的该特定方法。

这将阻止我的UI。

最佳答案

您所说的“这会降低应用程序性能”是什么意思。调用网络服务时,您的应用程序落后吗?这不是因为您在viewDidLoad中调用它,而是因为您正在主线程中执行该操作。

要调用您的网络服务,您可以使用:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{

// Call here your web service

    dispatch_sync(dispatch_get_main_queue(), ^{

    // push here the results to your ViewController

    });

});


通过这种简单的解决方案,您可以在单独的线程中从Web服务下载数据。然后使用mainThread将数据推送到您的ViewController。此代码不会冻结您的应用程序。但是,您将有片刻什么也不会发生。这是使用UIActivityIndicatorVew的好时机。

10-07 19:57
查看更多