我有一个壁纸应用程序,在主视图上有一个分页滚动视图。滚动视图的每一页显示 9 张图像。当视图滚动时,我正在加载接下来的 10 页图像并将之前加载的 10 页 uiimages 设置为 nil 以防止内存警告。
问题是当视图滚动时,滚动视图的以下方法被调用,即使我已将加载新图像的块代码放在 dispatch_async 中,视图滚动前也有几秒钟的延迟。当我用调度的东西注释掉代码的整个部分时,没有延迟。
如果有人知道为什么会发生这种情况。请让我知道。
非常感谢大家
- (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];
}
}
}
}
脑法imageWith:
-(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;
}