ios - Swift 后台执行选择器

标签 ios objective-c swift grand-central-dispatch nsobject

现在我注意到 [NSObject performSelectorInBackground] 不可用 在 Swift 中。

要在 Swift 中做一些后台操作,我可以使用什么
而不是performSelectorInBackground

我找到了 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{}),它可以替代 performSelectorInBackground 吗?

最佳答案

I found dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{}), can it be alternative of performSelectorInBackground?

是的。

其实还是有区别的。

NSObject -performSelectorInBackground:withObject: 方法总是使用 NSThread 产生一个新线程。

Using NSObject to Spawn a Thread

In iOS and OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could use the following code to do that:

[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];

The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see Configuring Thread Attributes.

相比之下,Grand Central Dispatch、Global Queue 更高效、更复杂。

Concurrency and Application Design

  • They offer automatic and holistic thread pool management.
  • They provide the speed of tuned assembly.
  • They are much more memory efficient (because thread stacks do not linger in application memory).

关于ios - Swift 后台执行选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31399323/

相关文章:

ios - 尝试按一个属性分组并获取核心数据中每组中的实体数

ios - didBeginContact 未被调用

ios - 从 Parse 对象设置 UIPickerView 中的选定行

objective-c - iOS 企业应用的奇怪问题

ios - 让 MPRemoteCommandCenter.shared() 在 tvOS 中工作

security - 在 Swift 中哪里可以安全地存储密码? CloudKit还好吗?

ios - 每当我点击里面的整个应用程序时播放点击声音

ios - UIAlertController 不弹出

objective-c - 如何从应用程序加载 xib 并显示自定义框架的窗口

ios - 在哪里初始化 UITablewView 作为 subview