iOS依赖(线程,队列)
依赖的作用: 在iOS开发中,我们经常会用到一个线程需要等待另一个结束才能进行的需求,这种需求其实有很实用的解决办法.下面我将列举一些目前用到的方法:
//需求:: 用NSOpertion和NSOpertionQueue处理A,B,C,D,E三个线程,要求执行完A,B,D,E后才能执行C,怎么做?
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// 创建5个操作
NSOperation *a = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"operation---a");
}];
NSOperation *b = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"operation---b");
}];
NSOperation *c = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"**************c");
}];
NSOperation *d = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"operation---d");
}];
NSOperation *e = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"operation---e");
}];
// 添加依赖
[c addDependency:a];
[c addDependency:b];
[c addDependency:d];
[c addDependency:e];
// 执行操作
[queue addOperation:a];
[queue addOperation:b];
[queue addOperation:c];
[queue addOperation:d];
[queue addOperation:e];
打印结果:
2017-08-17 18:38:02.040 依赖[11633:750843] operation---a
2017-08-17 18:38:02.040 依赖[11633:757610] operation---b
2017-08-17 18:38:02.040 依赖[11633:757611] operation---d
2017-08-17 18:38:02.040 依赖[11633:757612] operation---e
2017-08-17 18:38:02.042 依赖[11633:757610] **************c