我在这里遇到了一些问题,我让用户将一些视频上传到服务器但是我在管理我用来说明其进度的视图时遇到了一些困难,我知道为什么问题发生了我找到了解决方法(有点)我的问题
因此,如果有人试图制作一些类似于此的代码(在UIViewController中
)-(void)uploadMovie
{
UIActivityView indicator=new...
[self.view addSubview:indicator]
[uploader UploadMyMovie:data]
}
这段代码不起作用,上传器将锁定控制器,并且不会让时间让指示器及时进入屏幕,我发现在调用上传器工作之前等了几秒钟,但我采取了另一种方法。
方法是为上传者启动一个新线程,并有一个协议,上传者对象在开始上传,进度以及完成上传时通知UIViewController(或某个委托)。像
这样的东西 -(void)uploadMovie
{
UIActivityView indicator=new...
[self.view addSubview:indicator]
NSThread *thread=...
[thread start]
}
委托方法看起来像这样
#pragma mark UploadProgressDelegate
-(void)didStartUploading
{
progressLabel= [[UILabel alloc] initWithFrame:CGRectMake(93, 240, 116, 32)];
ind= [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
ind.center=self.view.center;
[progressLabel setTextColor:[UIColor blackColor]];
[progressLabel setText:@"TEST"];
[self.view addSubview:progressLabel];
[self.view addSubview:ind];
[ind startAnimating];
[self.view bringSubviewToFront:progressLabel];
[ind setHidesWhenStopped:TRUE];
[self.view setUserInteractionEnabled:FALSE];
}
-(void)progressUpdate:(NSString*)progress
{
[progressLabel setText:progress];
}
-(void)didEndUploading;
{
[progressLabel removeFromSuperview];
[ind stopAnimating];
[ind removeFromSuperview];
[progressLabel release];
[ind release];
[self.view setUserInteractionEnabled:TRUE];
}
这很好用,指示器显示和一切,然后我决定让用户通过添加UILabel(反映在上面的代码中)看到进度,但是为此解决方案不起作用,标签不显示和当然没有更新...
我想知道是否有人遇到过这种情况并提出了解决方案吗?或者如果你可以从上面的代码中看到为什么标签没有显示......
由于
答案 0 :(得分:1)
在某些情况下,我发现我需要回到主线程来做某些事情......
所以在你的委托方法中你要做
[self performSelectorOnMainThread: @selector(updateLabel:) withObject:newLabelText waitUntilDone:NO];
然后
- (void) updateLabel:(NSString *)newLabelText
{
[progressLabel setText:newLabelText];
}
我不确定在主线程上而不是在后台执行什么操作的规则是什么。
答案 1 :(得分:1)
UIKit不是线程安全的。如果您要更新UI元素,则需要同步回主线程或所有投注都已关闭。