我在viewDidLoad上调用一个属于自定义委托类的方法,但它从[sampleProtocol startSampleProcess]开始,从sleep(5)开始,然后再向我展示视图控制器和label1。
CustomDelegate *sampleProtocol = [[CustomDelegate alloc]init];
sampleProtocol.delegate = self;
[self.label1 setText:@"Processing..."];
[sampleProtocol startSampleProcess];startSampleProcess法在此基础上;
-(void)startSampleProcess{
sleep(5);
[self.delegate processCompleted];
}processCompleted法也在以下;
-(void)processCompleted{
[self.label1 setText:@"Process Completed"];
}它只是在视图控制器上设置一个标签,转到另一个类并做一些简单的事情(例如:睡眠),然后返回到查看控制器并再次设置标签。我以前没有试过定制委托,所以如果你能帮我解决我缺少的东西,那就太好了。
发布于 2015-03-22 17:02:36
问题是在主线程上调用sleep。
以下是iOS应用程序的工作方式:
这个应用程序有一个叫做runloop的程序,它接收来自系统的关于触摸、定时器等的消息。每次收到消息,它都运行一些代码,这些代码通常是由您提供的。调用sleep函数时,它将挂起当前线程。当线程挂起时,在完成sleep之前,run循环无法处理新事件。
当您在屏幕上更改某些内容时,将向run循环添加一个事件,该事件表示需要重新绘制屏幕。因此,这就是您的应用程序中正在发生的情况:
sleep时间为5秒,这意味着runloop无法处理新事件。如果任务需要长时间运行,可以在后台线程中完成:
-(void)startSampleProcess {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_NORMAL, 0) ^{ //run this code in the background so it doesn't block the runloop
sleep(5);
dispatch_async(dispatch_get_main_thread(), ^{ //after the task is done, call the delegate function back on the main thread since UI updates need to be done on the main thread
[self.delegate processCompleted];
});
});
}https://stackoverflow.com/questions/29196982
复制相似问题