我有一个包含一些GIF图像的viewController,加载这些图像需要花费大量内存,所以每次进入这个viewController都需要几秒钟,有什么方法可以先进入这个viewCOntroller然后加载数据?我不知道NSThread会不会起作用。我的英语很差,希望你能理解我的问题.Thx。
答案 0 :(得分:2)
是的,最简单的方法是使用盛大的中央调度
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ //enter a background thread
UIImage * img = [UIImage imageNamed:@"image.jpg"]; //load image in background
dispatch_sync(dispatch_get_main_queue(), ^{ //return to main thread
[[self imageView] setImage: img]; //set the imageViews image
});
});
答案 1 :(得分:1)
只需在viewDidAppear:
中编写代码或使用viewDidLoad
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Add your image creation code here e.g.
UIImage *image = [UIImage imageNamed:@"yourImage.png"];
dispatch_async( dispatch_get_main_queue(), ^{
// Add code here to update the UI
self.imageView = image;
});
});
答案 2 :(得分:1)
在ViewController的viewDidAppear方法中加载数据,因此View将首先显示而不显示GIFS,但是当您循环获取每个数据时,您可以在加载时将图像设置为视图。
答案 3 :(得分:1)
这样做。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// (BackGroungThred) here you can retrive the image from your sources . But do not update UI in backgroung thread ..
dispatch_sync(dispatch_get_main_queue(), ^{
// (Main Thread) Update UI in main thread..
});
});
希望对你有帮助..
答案 4 :(得分:1)
输入视图控制器后,有两个选项用于加载数据
1.NSOperationQueue
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
[myQueue addOperationWithBlock:^{
// Background work
UIImage * img = [UIImage imageNamed:@"image.jpg"];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Main thread work (UI usually)
yourImageView.image = image;
}];
}];
2.Grand Central Dispatch(GCD)
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
// Background work
UIImage * img = [UIImage imageNamed:@"image.jpg"];
dispatch_async(dispatch_get_main_queue(), ^(void)
{
// Main thread work (UI usually)
yourImageView.image = image;
});
});
有关详细信息,请参阅以下链接