gpt4 book ai didi

iOS 即使使用调度也会出现延迟

转载 作者:行者123 更新时间:2023-11-29 03:55:31 24 4
gpt4 key购买 nike

我有一个壁纸应用程序,在主视图上有一个分页 ScrollView 。 ScrollView 的每一页显示 9 个图像。当 View 滚动时,我将加载接下来的 10 页图像,并将已加载的前 10 页 uiimages 设置为 nil 以防止出现内存警告。

问题是当 View 滚动并且调用以下 ScrollView 方法时,即使我已将加载新图像的 block 代码放入dispatch_async, View 滚动之前也会有几秒钟的延迟。当我用调度内容注释掉整个代码部分时,没有延迟。

如果有人知道为什么会发生这种情况。请让我知道。

非常感谢大家

- (void)scrollViewDidScroll:(UIScrollView *)scrollV
{
float fractionalPage = scrollView.contentOffset.x / self.view.frame.size.width;

if (curPageNum != lround(fractionalPage)) {

curPageNum = lround(fractionalPage);

//display the page number
pageNumLabel.text = [NSString stringWithFormat:@"%d",curPageNum+1];
pageNumLabel.alpha = 1.0;
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dismissPageNum) userInfo:nil repeats:NO];


//loading more pages with 9 image in each
lastLoadedPageNum = MIN(lastLoadedPageNum + 10, numPages - 1);

dispatch_queue_t getImages = dispatch_queue_create("Getting Images", nil);
dispatch_async(getImages, ^{

for (int i = curPageNum + 4 ; i <= lastLoadedPageNum ; i++) {

int numPicsPerPage = 9;
if (picsNames.count%9 && i == numPages-1) {

numPicsPerPage = picsNames.count%9;
}

for (int j = 0 ; j < numPicsPerPage ; j++) {

UIImage *image = [brain imageWith:[picsNames objectAtIndex:(i*9) + j]];

dispatch_async(dispatch_get_main_queue(), ^{

//loading the image to imageview
UIImageView *imageView = (UIImageView *)[scrollView viewWithTag:IMAGE_VIEWS_TAG + (i*9) + j];
imageView.image = image;
});
}
}
});

//setting old imageview images to nil to release memory
int oldFirstLoadedPageNum = firtLoadedPageNum;
firtLoadedPageNum = MAX(curPageNum - 4, 0);
for (int i = oldFirstLoadedPageNum ; i < firtLoadedPageNum ; i++) {

int numPicsPerPage = 9;
if (picsNames.count%9 && i == numPages-1) {

numPicsPerPage = picsNames.count%9;
}

for (int j = 0 ; j < numPicsPerPage ; j++) {

UIImageView *imageView = (UIImageView *)[scrollView viewWithTag:IMAGE_VIEWS_TAG + (i*9) + j];
imageView.image = nil;
[((UIActivityIndicatorView *)[imageView viewWithTag:ACTIVITY_INDICATOR_TAG]) startAnimating];
}
}
}
}

脑法图像:

-(UIImage *)imageWith:(NSString *)imageName
{
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:imageName];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

if (!image && [self connected]) {

image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", picsURL, imageName]]]];

if (image) {

[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
}

}

return image;
}

最佳答案

显然您的代码正在循环,这导致了延迟。我认为由于调度位于 for 循环内部,因此仅在一定的迭代之后才会调用它,因此在这里使用多线程没有真正的好处。

关于iOS 即使使用调度也会出现延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16552011/

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