gpt4 book ai didi

iphone - iOS 中的 NSThread 问题

转载 作者:行者123 更新时间:2023-12-03 20:00:35 25 4
gpt4 key购买 nike

我有一个应用程序,可以将多个缩略图加载到 UIScrollVIew 中。这是一个冗长的操作,为了不阻塞 UI 其余部分的显示,我在单独的线程中运行它。这在应用程序启动时第一次工作正常,但后来需要将一组新图像加载到 UIScrollView 中。当我第二次分离线程时,应用程序崩溃(有时)。代码如下:

// this call is in a separate method
[NSThread detachNewThreadSelector:@selector(addThumbnailsToScrollView) toTarget:self withObject:nil];


// this is the main entry point for the thread
- (void) addThumbnailsToScrollView {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Top-level pool

// now place all the thumb views as subviews of the scroll view
float xPosition = THUMB_H_PADDING;
int pageIndex = 0;
for (Page *page in self.pages) {

// get the page's bitmap image and scale it to thumbnail size
NSString *name = [page valueForKey:@"pageBackground"];
NSString *basePath = [[NSBundle mainBundle] pathForResource:page.pageBackground ofType:@"jpg" inDirectory:nil];
UIImage *thumbImage = [UIImage imageWithContentsOfFile:basePath];
thumbImage = [thumbImage imageScaledToSize:CGSizeMake(80, 100)];

// create a ThumbImageView for each page and add it to the thumbnailScrollView
if (thumbImage) {
ThumbImageView *thumbView = [[ThumbImageView alloc] initWithImage:thumbImage];
[thumbView setDelegate:self];
[thumbView setImageName:name];
[thumbView setImageSize:CGSizeMake(80, 100)];
[thumbView setPageIndex:pageIndex];
pageIndex ++;
CGRect frame = [thumbView frame];
frame.origin.y = 0;
frame.origin.x = xPosition;
[thumbView setFrame:frame];
[thumbnailPagesScrollView addSubview:thumbView];
[thumbView release];
xPosition += (frame.size.width + THUMB_H_PADDING);
}
}

[self hightlightThumbnailPageAtIndex:0];
[(UIActivityIndicatorView *)[thumbnailPagesScrollView.superview viewWithTag:100] stopAnimating];

[pool release]; // Release the objects in the pool.
}

我认为一旦主入口例程完成,分离的线程就会退出。第二次分离线程的调用不是一个新线程吗?为什么应用程序会崩溃,但有时却不会?

谢谢

Jk

最佳答案

您无法在辅助线程中触摸 UIKit (即 UIScrollVIew) - 您需要重新组织,以便在辅助线程中进行提取,但您创建了一个 NSData 对象(包含图像二进制文件)可用于每个缩略图的主线程,以便它可以执行与实际显示它们相关的所有操作。

Apple 在文档中反复警告 UIKit 不是线程安全的。

关于iphone - iOS 中的 NSThread 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3860129/

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