gpt4 book ai didi

ios - 在主线程上执行 dispatch_async 后 UI 没有立即更新?

转载 作者:行者123 更新时间:2023-12-01 19:01:58 25 4
gpt4 key购买 nike

这是我的代码:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
for (int i = 0; i < size; i++)
{

CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.size = self.scrollView.frame.size;

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@x%@%@",
// some web service data

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];

UIView *subview = [[UIView alloc] initWithFrame:frame];

imageView.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.bounds.size.width, self.view.bounds.size.height);
[subview addSubview:imageView];
[self.dataViewsArray addObject:subview];
NSLog(@"dwonload bacgraound");

}

dispatch_async(dispatch_get_main_queue(), ^(void){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(@"starting some UI updates");
[self makeScrollPagingView];


});
});

[self makeScrollPagingView] - 只是将 subview 添加到我的 ScrollView 中?
我的代码完成后有 10 秒的延迟。然后更新ui。请帮忙

最佳答案

更快的解决方案是不同时加载图像,而是并行加载:

for (int i = 0; i < size; i++) {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@""]]];
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
CGImageRef imageRef = CGImageCreateWithPNGDataProvider(provider, NULL, false, kCGRenderingIntentDefault); // assuming PNG format, JPG is also available
CGDataProviderRelease(provider);

dispatch_async(dispatch_get_main_queue(), ^(void){
UIImage *image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);

UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Layout and position of just this UIImageView
});
});
}

但是,根据您的用途,这可能是以牺牲可读性/简单性为代价的过早优化。在主线程上创建 UIImage 可能就足够了。
for (int i = 0; i < size; i++) {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@""]]];

dispatch_async(dispatch_get_main_queue(), ^(void){
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
// Layout and position of just this UIImageView
});
});
}

您是否布局代码不依赖于一次加载所有图像。就像 Sashcha 所说,永远不要在后台线程中编写与 UI 相关的代码。

一些 UIImageView 库或类别可能会简化您需要编写的代码。 AFNetworking是一个很好的开始,它有 UIImageView+AFNetworking你应该看看。

关于ios - 在主线程上执行 dispatch_async 后 UI 没有立即更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22184164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com