希望这是一个合适的问题。我的目标是
1.add a controller into an array name 'arrControllers'
2.access and get current controller from 'arrControllers' to do sth with it
我只是想确保 arrControllers
在我访问和使用它之前应该准备就绪。这就是我使用 serial queue
和 dispatch_sycn
的原因,如下所示。
-(void)viewDidLoad
{
[super viewDidLoad];
firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
[self setUpWithView:firstViewController];
}
在 setUpWithView:
中是
-(void)setUpWithView:(UIViewController*)viewController {
dispatch_queue_t queue;
queue = dispatch_queue_create("my queue", NULL);
containerController = [ContainerViewController sharedContainerController];
// What I am taking about is from now on
dispatch_sync(queue, ^{
[containerController initWithRootViewController:viewController];
});
dispatch_sync(queue, ^{
[containerController setUpView];
});
}
和initWithRootViewController:
是
- (void)initWithRootViewController:(UIViewController*)rootViewController {
arrControllers = [[NSMutableArray alloc] init];
arrControllers = [NSMutableArray arrayWithObject:rootViewController];
}
和setUpView
是
-(void)setUpView {
/* Process to ADD currentController TO hierarchy */
[self addChildViewController:[arrControllers lastObject]];
............................................................
}
据我所知,编译器会逐行执行代码,这意味着执行以下操作
-(void)setUpWithView:(UIViewController*)viewController {
containerController = [ContainerViewController sharedContainerController];
// Not using serial_queue and dispatch_sync
[containerController initWithRootViewController:viewController];// line1
[containerController setUpView]; //line2
}
编译器将执行第 2 行,直到它完成第 1 行的任务。
我的问题是
1. is it necessary to using `serial_queue` and `dispatch_sycn`for this situation.
PS:如果你觉得这个问题不好问。请发表您的看法。
最佳答案
首先,你应该看看UIView
和 UIViewController
生命周期,这会告诉你什么时候 UIVie
或 UIViewController
是“准备好使用”。其次,您应该检查何时使用串行查询和 GCD。
对于第二点,我可以给你一个简短的总结,因为它比第一点要快一些。
如果您想在不卡住 UI 的后台线程上进行计算或其他不涉及 UI 更改的事情,请使用 CGD 和队列(主队列除外)。
将 GCD 与主队列结合使用,以在后台队列和主 (UI) 队列之间切换。
所有 UI 操作都必须在主线程上执行。
所以在你的情况下,你想创建一个 View Controller 并将它存储到一个数组中,所以作为一个建议,你的 View Controller 的所有 UI 相关调用都应该在 UI 线程上执行,所以不需要 GCD 或后台线程。
如果你在 View Controller 的 init
上做一些复杂的事情方法,只需将那些复杂的东西放在单独线程的 GCD block 中。
关于ios - 是否有必要在这里使用 dispatch_queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601528/