在这种情况下主队列/当前队列和主线程/后台线程之间的区别?

Nor*_*der 3 queue multithreading objective-c ios

我正在执行以下方法:

MotionHandler.m

-(void)startAccelerationUpdates
{
    [motionManagerstartDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]withHandler:^(CMDeviceMotion *motion, NSError *error){.....}
}
Run Code Online (Sandbox Code Playgroud)

在后台线程上,如下所示:

[currentMotionHandler performSelectorInBackground:@selector(startAccelerationUpdates) withObject:nil];
Run Code Online (Sandbox Code Playgroud)

但是上面的方法使用main Queue(在主线程上)来执行必要的更新,即使我在后台线程上调用它.所以加速更新是在后台线程或主线程上执行的,I'我很困惑..?

更有趣的是,当我再次在后台线程上调用上面的方法时,但是这次使用了current Queue,我得不到更新.有人可以解释一下运行之间的区别:

 1. a background thread but on the main queue

 2. a background thread but on the current queue 

 3. the main thread but on the main queue  

 4. the main thread but on the current queue
Run Code Online (Sandbox Code Playgroud)

在目前的实施?谢谢!

Dav*_*d H 5

我会试一试.首先,在没有被NSOperationQueue类引用告知的情况下,我们无法推断出'mainQueue'将在哪个线程上运行.阅读它我们看到实际上队列在mainThread(UI使用的那个)上运行其操作,因此您可以更新发布到该队列的操作中的UI.虽然它没有说明,但这些操作必须是串行的,因为它们是由runLoop执行的(它们可能也会被抢占,而不是100%肯定).

currentQueue的目的是使运行操作可以确定它们所在的队列,因此它们可以在该队列上对新操作进行排队.

  1. 后台线程但在主队列上

不可能 - NSOperation的mainQueue始终与mainThread相关联.

  1. 后台线程但在当前队列上

当您创建NSOperationQueue并向其添加NSOperations时,它们将在队列管理的后台线程上运行.任何给定的操作都可以查询它所在的线程,并且该线程在运行时不会更改.也就是说,该队列上的第二个操作可能会在另一个线程上运行.

  1. 主线程但在主队列上

见1)

  1. 主线程但在当前队列中

如果将操作排队到mainQueue(我们知道它总是在mainThread上),并且您要求currentQueue,它将返回mainQueue:

[NSOperationQueue currentQueue] == [NSOperationQueue mainQueue];
Run Code Online (Sandbox Code Playgroud)