iOS Block & Multi-threading

Code Block

A code of block starting with ^ can be passed as a parameter to a method

[obj method1:^(id value) {
    ...
}];
- m1 {
  NSString *v;
  [obj m2:^(id value) {
     // Able to access v
     [v ...];
  }];
}
  • Can read variables v declared before the method
  • Variable v will be retained and accessible even the m1 exists
    • Since the code block may be called later, v is still valid when the block is invoked

Code block taking parameter

  [obj m2:^{
    ...
  }];

Store a code block as a variable

typedef double (^op)(double value);

op m;
m = ^(double value) {
    return value * value;
}
[m 5];
- m2:(op)m

Assign a code block to a variable

double (^op)(double value) = ^(double value) { return value * value; };

iOS Multithreading

Spawn a new thread in processing non-UI Operation

dispatch_queue_t myQueue = dispatch_queue_create("my op thread", NULL);

dispatch_async(myQueue, ^{
       // Non-UI Operation
       ...
});

dispatch_release(myQueue);

Since UI operations must be run in the main thread, dispatch the UI operation in the main thread

dispatch_queue_t myQueue = dispatch_queue_create("my op thread", NULL);

dispatch_async(myQueue, ^{
  // Non-UI Operation
  ...

  dispatch_async(dispatch_get_main_queue(), ^{
  // UI Operation
     ...
  });
});

dispatch_release(myQueue);