简体   繁体   中英

performSelectorInBackground in Swift

Now I noticed that [NSObject performSelectorInBackground] is unavailable in Swift.

To do somethings in background in Swift, what can I use
instead of performSelectorInBackground ?

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

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

Yes.

As a matter of fact, there is difference.

NSObject -performSelectorInBackground:withObject: method always spawn a new thread using 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.

By contrast, Grand Central Dispatch, Global Queue is more efficient, more sophisticated.

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).

Use below code

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),{

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM