![](/img/trans.png)
[英]What's the best way to load data for a ViewController before navigating to it?
[英]What is the best way to load data inside a Viewcontroller
我正在編寫一個從服務器獲取數據的iOS應用程序。 我有幾個ViewControllers
。 我曾經在viewDidLoad
方法下為該viewcontroller加載數據
-(void)ViewDidload
{
[self loadData];
}
-(void)loadData
{
//calling to webservice caller class
}
但這會降低應用程序的性能。 在viewcontroller中加載數據的最佳方法是什么? 對於webservice調用,我有一個單獨的類。 在我的loadData
方法中,我調用webservice調用類中的特定方法。
這會阻止我的UI。
“ 這會降低應用程序性能 ”是什么意思? 當您撥打網絡服務時,您的應用程序是否滯后? 這不是因為你在viewDidLoad
中調用它,這是因為你在主線程中這樣做。
要調用您的Web服務,您可以使用:
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
的好時機。
我想你的界面是滯后的。 嘗試這個:
-(void)ViewDidload
{
[NSThread detachNewThreadSelector:@selector(loadData) toTarget:self withObject:nil];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.