我在使用 addOperationWithBlock
时遇到了一些奇怪的结果。
我的函数看起来像这样:
-(void) myFunction{
NSLog(@"VISITED");
..
for (NSDictionary *Obj in myObjects)
{
[operationQueue addOperationWithBlock:^(void){
MyObject* tmp = [self tediousFunction:Obj];
// threadTempObjects is member NSMutableArray
[self.threadTempObjects addObject:tmp];
NSLog(@"ADDED");
}];
}
[operationQueue addOperationWithBlock:^(void){
[self.myArray addObjectsFromArray:self.threadTempObjects];
for(myObject *myObj in self.myArray)
{
// MAIN_QUEUE
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
[self updateUI:myObj];
}];
}
}];
[operationQueue addOperationWithBlock:^(void){
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
[self filterResults];
}];
}];
}
我的字典包含 4 个值,因此 ADDED 在日志中显示 4 次。 但是, 当我查看 filterResults 内部时,我发现 myArray 中只有 2 个对象。意思是4次调用operationQueue并没有在调用filterResults操作之前结束(虽然是后来加的!)
我认为 operationQueue 是串行的,我可以指望它,当我添加一个操作时,它会在最后一个操作之后立即添加。 所以奇怪的是,在之后的数组中只有 2 个操作。 我错过了什么?谢谢
最佳答案
从您共享的初始化代码中我们可以了解到 operationQueue
不是串行的,这意味着它将执行操作,并分配线程直到系统设置最大线程数(与 GCD 相同) .
这意味着添加到 operationQueue
的操作是并行运行的。
要连续运行它们,请将 maxConcurrentOperationCount
设置为 1。
尝试类似的东西:
__block __weak id weakSelf = self;
[operationQueue setMaxConcurrentOperationCount:1];
for (NSDictionary *Obj in myObjects)
{
[operationQueue addOperationWithBlock:^{
MyObject* tmp = [weakSelf tediousFunction:Obj];
// threadTempObjects is member NSMutableArray
[weakSelf.threadTempObjects addObject:tmp];
NSLog(@"ADDED");
}];
}
[operationQueue addOperationWithBlock:^{
[weakSelf.myArray addObjectsFromArray:weakSelf.threadTempObjects];
for(myObject *myObj in weakSelf.myArray)
{
// MAIN_QUEUE
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
[weakSelf updateUI:myObj];
}];
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
[weakSelf filterResults];
}];
}
}];
但是,这等同于(甚至效率更低):
__block __weak id weakSelf = self;
[operationQueue addOperationWithBlock:^{
for (NSDictionary *Obj in myObjects) {
MyObject* tmp = [weakSelf tediousFunction:Obj];
// threadTempObjects is member NSMutableArray
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
[weakSelf updateUI:tmp];
}];
[weakSelf.myArray addObject:tmp];
NSLog(@"ADDED");
}
[[NSOperationQueue mainQueue] addOperationWithBlock:^(void) {
[weakSelf filterResults];
}];
}];
关于ios - addOperationWithBlock 的操作顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884690/