Full details GCD Series (ii) dispatch_after;dispatch_apply;dispatch_once

Source: Internet
Author: User

First, Dispatch_after
Function: Delay the execution of a task in a queue for a period of time and cannot be canceled after it is returned
Often used to defer a task on the main queue
Function prototypes

[Plain] View PlainCopy
    1. Func Dispatch_after (_ when:dispatch_time_t,
    2. _ Queue:dispatch_queue_t!,
    3. _ block:dispatch_block_t!)

Parameters

[Plain] View PlainCopy
    1. How long after the time interval of execution
    2. Queues submitted to queue
    3. Tasks performed by block



For example, you can use Dispatch_after to write a delay function of your own, delay a period of time on the main thread to execute a piece of code

[Plain] View PlainCopy
    1. func hwcdelay (delay:double, closure: ())  {  
    2.     dispatch_after (  
    3.          dispatch_time (  
    4.              dispatch_time_now,  
    5.              int64 (Delay * double (nsec_per_sec))   
    6.          ),   
    7.          dispatch_get_main_queue (),  closure)   
    8. }  


Only need to use this
Hwcdelay (0.5) {
Do everything want
}
For example, when the user's app does not meet some of the requirements of our app (for example, our app needs Bluetooth to open), and then when the app starts to test Bluetooth off, you should give the user a hint. After the view loading is completed, delay to the user a hint, you can also add some animation to this hint, it is more than the view in the load to complete the direct display prompt is much better.
Example
After viewload, delay 1s, prompting a alertview

[Plain] View PlainCopy
  1. Class viewcontroller:uiviewcontroller{
  2. Func Hwcdelay (delay:double, Closure: ()) {
  3. Dispatch_after (
  4. Dispatch_time (
  5. Dispatch_time_now,
  6. Int64 (Delay * Double (NSEC_PER_SEC))
  7. ),
  8. Dispatch_get_main_queue (), closure)
  9. }
  10. Override Func Viewdidload () {
  11. Super.viewdidload ()
  12. Hwcdelay (1.0) {
  13. var Alertview = Uialertview (title: "Dispatch_after", Message: "Message", Delegate:self,cancelbuttontitle: "OK")
  14. Alertview.show ()
  15. }
  16. }
  17. Override Func didreceivememorywarning () {
  18. Super.didreceivememorywarning ()
  19. }
  20. }


Second, dispatch_apply
Function: Commits a task to the queue multiple times, whether parallel execution or serial execution is determined by the queue itself. Note that dispatch_apply does not return immediately after execution, and is a synchronous call.

[Plain] View PlainCopy
    1. Func dispatch_apply (_ Iterations:uint,
    2. _ Queue:dispatch_queue_t!,
    3. _ Block: ((UInt), Void)!)

Parameters

[Plain] View PlainCopy
    1. Number of iterations executions
    2. Queues submitted to queue
    3. Tasks performed by block


So, when do you use this function? It is not difficult to see from its function that if we can commit unrelated loops to the background thread execution in parallel, and the efficiency of the cyclic task scheduling to the background execution, can offset the overhead of the queue scheduling itself, then the efficiency will be significantly improved.

Example
For example, I have an array that stores a series of objects, and when initialized, these objects call a function once to perform the relevant calculations. These calculations have no effect on each other. At this point, we can use the dispatch_apply to initialize with an asynchronous queue. This simplifies the situation here.

[Plain] View PlainCopy
  1. Class viewcontroller:uiviewcontroller{
  2. var hwcarray = ["Hello", "HWC", "HELLOHWC"]
  3. Override Func Viewdidload () {
  4. Super.viewdidload ()
  5. Dispatch_apply (3,dispatch_get_global_queue (dispatch_queue_priority_default,0)) {
  6. (Index:uint), () in
  7. var expobject = self.hwcarray[int (index)] as NSString
  8. NSLog ("%d", expobject.length)
  9. }
  10. NSLog ("Dispatch_after is Over")
  11. }
  12. Override Func didreceivememorywarning () {
  13. Super.didreceivememorywarning ()
  14. }
  15. }

As you can see, the output is

[Plain] View PlainCopy
    1. 3
    2. 5
    3. 8
    4. Dispatch_after is Over

Because this blocks the main thread, and the following is not relevant to the dispatch_apply execution results, you can drop dispatch_apply in the asynchronous queue and then notify when the execution is complete

[Plain] View PlainCopy
  1. Class viewcontroller:uiviewcontroller{
  2. var hwcarray = ["Hello", "HWC", "HELLOHWC"]
  3. Override Func Viewdidload () {
  4. Super.viewdidload ()
  5. Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default,0)) {
  6. Dispatch_apply (3,dispatch_get_global_queue (dispatch_queue_priority_default,0)) {
  7. (Index:uint), () in
  8. var expobject = self.hwcarray[int (index)] as NSString
  9. NSLog ("%d", expobject.length)
  10. }
  11. NSLog ("Dispatch_after in global queue are over")
  12. }
  13. NSLog ("Dispatch_after in main queue are over")
  14. }
  15. Override Func didreceivememorywarning () {
  16. Super.didreceivememorywarning ()
  17. }
  18. }

This output is

[Plain] View PlainCopy
    1. 8
    2. Dispatch_after in main queue are over
    3. 3
    4. 5
    5. Dispatch_after in global queue are over

As you can see, the Relative Home column (main thread) is asynchronous and is executed in parallel in the global queue
Third, dispatch_once
Function: ensure that the code in the block executes only once during the app run
Func Dispatch_once (_ Predicate:unsafemutablepointer<dispatch_once_t>,
_ block:dispatch_block_t!)
Parameters
predicate is used to determine if the committed block is completed
Block performs a task once
Dispatch_once's classic practical scenario is a single case
Single-Case Code:

[Plain] View PlainCopy
  1. Class Hwcsingleton {
  2. var testvariable:int!
  3. Func print () {
  4. testvariable = testvariable + 1
  5. println (testvariable)
  6. }
  7. class Var Sharedobject:hwcsingleton {
  8. struct Staticstruct {
  9. static var predicate:dispatch_once_t = 0
  10. static Var Instance:hwcsingleton? = Nil
  11. }
  12. Dispatch_once (&staticstruct.predicate) {
  13. Staticstruct.instance = Hwcsingleton ()
  14. Staticstruct.instance?. TestVariable = 10
  15. }
  16. Return staticstruct.instance!
  17. }
  18. }

Full details GCD Series (ii) dispatch_after;dispatch_apply;dispatch_once

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.