使用-performSelector时是否存在并发问题:withObject:afterDelay:?

时间:2010-05-16 10:06:13

标签: iphone multithreading

例如,我经常使用它:

[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:someDelay];

现在,让我说我打电话10次以完全相同的延迟,如:

[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];
[self performSelector:@selector(doSomethingAfterDelay:) withObject:someObject afterDelay:2.0];


- (void)doSomethingAfterDelay:(id)someObject {
   /*
   access an array, read stuff, write stuff, do different things that would suffer in multithreaded environments .... all operations are nonatomic!
   */
}

在做这样的事情时,我发现了很奇怪的行为。根据我的理解,这个方法安排一个计时器来触发当前线程,所以在这种情况下是主线程。但由于它不会创建新线程,实际上不应该遇到并发问题,对吧?

2 个答案:

答案 0 :(得分:5)

简短回答。是的 - 不应该遇到并发问题。 performSelectorWithObjectAfterDelay在主线程上执行(并阻止UI)。但是,在上面的示例中,我不想猜测它们会运行的顺序 - 许多调用可以在运行循环的同一圈进行调度。

答案 1 :(得分:2)

您可能需要查看NSOperationNSOperationQueue。您可以将队列设置为一次运行一个并发操作,队列将按添加顺序执行操作。

通过KVO,您可以跟踪每个操作'isFinished属性,并在操作触发isFinished时修改/更新主线程上的对象。