NSIncationOperation 和主线程
想象一下,我有一个视图,其中某个 UIKit 对象作为其子视图(例如,UIActivityIndicatorView
- 这并不重要)。该视图还有一个名为 doSomething
的选择器,它以某种方式管理 UIKit 对象(在我们的示例中,它可以启动或停止指示器视图)。
我使用 initWithTarget:self selector:@selector(doSomething) object:nil
创建 NSInitationOperation
(从视图的代码部分)。然后将其添加到NSOperationQueue
。一切都很好。
如何?!它应该是一个新的线程和非线程安全的 UIKit 对象!为什么没有发现错误(并且没有发生崩溃)?
Imagine that I have a view with some UIKit object as its subview (for example, UIActivityIndicatorView
- this doesn't matter). This view also has a selector, called doSomething
, which somehow manages UIKit object (in our example it can start or stop indicator view).
I create NSInvocationOperation
(from view's code parts) with initWithTarget:self selector:@selector(doSomething) object:nil
. Then add it to NSOperationQueue
. And all works fine.
How?! It should be a new thread and non-thread-safe UIKit object! Why no error found (and no crash happened)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSInitationOperation
类是NSOperation
的具体子类,实现非并发操作。在非并发操作中, 操作的任务是同步执行的 - 也就是说,操作对象不会创建单独的线程来运行任务。因此,当调用非并发操作的
start
方法时,该操作会立即在当前线程中执行。当此类对象的start
方法将控制权返回给调用者时,任务本身就已完成。但是,使用 NSOperationQueue 会改变这种行为。 NSOperationQueue 总是并发执行操作;非并发操作需要一个单独的线程才能并发执行,而 NSOperationQueue 提供了这个线程。
这意味着,如果您直接执行
NSInitationOperation
,您就能够以线程安全的方式访问 UIKit 对象(该操作将在同一线程上运行)。在您的情况下,如果使用NSOperationQueue
,您应该使用 NSObject 的 performSelectorOnMainThread:withObject:waitUntilDone:< /a> 来自您的调用选择器。The
NSInvocationOperation
class is a concrete subclass ofNSOperation
that implements a non-concurrent operation.In a non-concurrent operation, the operation’s task is performed synchronously—that is, the operation object does not create a separate thread on which to run the task. Thus, when the
start
method of a non-concurrent operation is called, the operation executes immediately in the current thread. By the time thestart
method of such an object returns control to the caller, the task itself is complete.However, using
NSOperationQueue
changes this behavior. NSOperationQueue always executes operations concurrently; a non-concurrent operation requires a separate thread in order to execute concurrently, andNSOperationQueue
provides this thread.This means that if you'd execute your
NSInvocationOperation
directly, you'd be able to access your UIKit object thread-safe(the operation would run o the same thread). In your case, if using aNSOperationQueue
, you should schedule the work that uses the UIKit object on the main thread, using NSObject's performSelectorOnMainThread:withObject:waitUntilDone: from your invocation selector.