objective-c blocks as object for performSelectorOnMainThread

Here :
#1 blocks overview
#2 blocks have lexical scope
#3 definition
#4 example : performSelectorOnMainThread

#1 Blocks overview

Block is an object that encapsulates a portion of code.

^{ <obj-c block code> }

Each time you want to pass as argument a piece of code to a method you can use blocks. In the same way if you want to assign to a variable a portion of code then you can use again blocks. Using a pseudocode:

[ object doThisActions:^{ <obj-c block code> } ];

#2 Blocks have lexical scope

Blocks have lexical scope. This mean that codes in a block <obj-c block code> has access to local variables in the same scope where block is defined/wrote.  So if you pass a block as argument of a method then your <obj-c block code>, when executed at run-time, has access to variables present at definition point. Block brings all variables “copied”. But by default access to those variables are read-only. If you want to have write-access you have to use  __block : if you declare a variable with the __block modifier, then you can change its value within the block.

{   ...
    __block char charCanBeChanged; // local variable
    void (^myBlockName)(void) = ^(void) { // definition of block
      charCanBeChanged = '\0'; //<obj-c block code> has access to local variable 

Just as background there are two sort of scope :

  • Lexical scoping : scope is referred to static program text
  • Dynamic scoping : scope is referred to dynamic flow of execution

More here (click-here) from apple.

#3 Definition

The start of a block is specified using char : ^
Basically there are two  types of definition for blocks:

 Inline : as a argument of a method

withObject:^{return updateThisPosition;}…

[self performSelectorOnMainThread: @selector(wrapperForUpdateRendering:)
  withObject:^{return updateThisPosition;}

Variable assignment:  blocks are defined as a variable

int (^myBlockName)(void) = ^(void) {…

int (^myBlockName)(void) = ^(void) { return updateThisPosition; };
[self performSelectorOnMainThread:@selector(wrapperForUpdateRendering:)
  withObject:myBlockName   //myBlockName is the variable associated to block
Blocks definition structure
Blocks definition structure

#4 Example : performSelectorOnMainThread

NSInteger updateThisPosition = ...;
[self performSelectorOnMainThread:@selector( wrapperForUpdateRendering: )
withObject:^{return updateThisPosition;}
-(void)wrapperForUpdateRendering:(NSInteger (^)(void))myBlockName{
 NSInteger wposition = myBlockName(); //myBlockName is the variable associated to block passed as argument
 [self updateRendering:wposition];

In this example performSelectorOnMainThread invokes wrapperForUpdateRendering  passing as argument block: ^{return updateThisPosition;}. wrapperForUpdateRendering uses that block myBlockName(); in order to get updateThisPosition and redraw rendering (OnMainThread).

User Review
0 (0 votes)