例如,我经常使用它:
[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!
*/
}
在做这样的事情时,我发现了很奇怪的行为。根据我的理解,这个方法安排一个计时器来触发当前线程,所以在这种情况下是主线程。但由于它不会创建新线程,实际上不应该遇到并发问题,对吧?
答案 0 :(得分:5)
简短回答。是的 - 不应该遇到并发问题。 performSelectorWithObjectAfterDelay在主线程上执行(并阻止UI)。但是,在上面的示例中,我不想猜测它们会运行的顺序 - 许多调用可以在运行循环的同一圈进行调度。
答案 1 :(得分:2)
您可能需要查看NSOperation
和NSOperationQueue
。您可以将队列设置为一次运行一个并发操作,队列将按添加顺序执行操作。
通过KVO,您可以跟踪每个操作'isFinished
属性,并在操作触发isFinished
时修改/更新主线程上的对象。