Iphone多线程-如何从后台线程更新界面(主线程)中的事件?
1.我的主视图是UIScrollView。我必须加载9个图像作为瓷砖到它 2.我以不同线程的形式调用该函数,以获取9images并将其加载到接口(主线程)中。通过这样做,接口保持响应 3.但问题是,即使在加载图像时,在整个线程完成之前,图像也不会显示在UIScrollView中。但是,如果我在界面上执行一些操作,我可以看到它们中的每一个都被加载和显示Iphone多线程-如何从后台线程更新界面(主线程)中的事件?,iphone,nsthread,Iphone,Nsthread,1.我的主视图是UIScrollView。我必须加载9个图像作为瓷砖到它 2.我以不同线程的形式调用该函数,以获取9images并将其加载到接口(主线程)中。通过这样做,接口保持响应 3.但问题是,即使在加载图像时,在整个线程完成之前,图像也不会显示在UIScrollView中。但是,如果我在界面上执行一些操作,我可以看到它们中的每一个都被加载和显示 这意味着在每个图像加载到界面中后,我必须从后台线程更新界面(主线程) 我怎么做?我已经给出了用于将图像加载到UIScrollView的代码,我使用
- (void)setUpDisplay:(NSArray *)array
{
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
myScrollView.userInteractionEnabled = YES;
myScrollView.multipleTouchEnabled = YES;
int x=0,y=0;
CGRect frame;
for (i = 0; i < 3; i++)
{
if(j == 3)
{
x=x+256;
y = y-768;
}
for (j = 0; j < 3; j++) {
imageView = [[UIImageView alloc] initWithImage:[self getCachedImage:[NSString stringWithFormat:@"url to fetch images"]]];
frame = [imageView frame];
frame.origin.x = x;
frame.origin.y = y;
[imageView setFrame:frame];
imageView.userInteractionEnabled = YES;
imageView.multipleTouchEnabled = YES;
[myScrollView addSubview:imageView];
y = y+256;
[imageView release];
imageView=nil;
}
}
[pool release];
}
-(无效)设置显示:(NSArray*)数组
{
NSAutoreleasePool*池=[[NSAutoreleasePool alloc]init];
myScrollView.userInteractionEnabled=是;
myScrollView.multipleToTouchEnabled=是;
int x=0,y=0;
CGRect帧;
对于(i=0;i<3;i++)
{
如果(j==3)
{
x=x+256;
y=y-768;
}
对于(j=0;j<3;j++){
imageView=[[UIImageView alloc]initWithImage:[self-getCachedImage:[NSString stringWithFormat:@“获取图像的url”]];
帧=[imageView帧];
frame.origin.x=x;
frame.origin.y=y;
[图像视图设置帧:帧];
imageView.userInteractionEnabled=是;
imageView.MultipleToTouchEnabled=是;
[myScrollView添加子视图:imageView];
y=y+256;
[图像视图发布];
imageView=nil;
}
}
[池释放];
}
NSObject的这种方法通常很有用:
[someObject performSelectorOnMainThread:@selector(updateUI:) withObject:anotherObject waitUntilDone:YES /* or NO */];
每次图像加载完成后,您可能希望尝试在主线程上调用[myScrollView setNeedsDisplay]。在后台线程中,即在函数中,我又添加了一行。[self-performSelectorOnMainThread:@selector(updateUI)with object:nil waitUntilDone:YES];并编写了另一个函数-(void)updateUI{[myScrollView setNeedsDisplay];}仍然无效。如果滚动视图所做的只是向其中添加子视图,则不需要使用-setNeedsDisplay手动重新绘制滚动视图。子视图应自动显示-setNeedsDisplay仅在该视图的-drawRect:中存在需要重新绘制的内容时才有用。[self-performSelectorOnMainThread:@selector(updateUI)with object:nil waitUntilDone:YES];并编写了另一个函数-(void)updateUI{[myScrollView setNeedsDisplay];}仍然无效。您希望在该实现中将WaitUntilOne设置为“否”,以避免在等待主线程更新时出现后台线程块。我发现,如果看不到由后台线程导致的UI更新,这通常就是问题所在。