Friday, September 28, 2012

Blocks


Blocks

^(double div, double divisor) {
  double quotient = div / divisor;
  return quotient;
};

^: identifies a block

Block can take arguments

If you want to access a block by a name, we have to assign it to a block variable.

void (^devow) (id, NSUInteger, BOOL *)
Block variable declaration


notice that the block assignment ends with a semi-colon just like any variable assignment would.

You can use typedef to declare a block at the start of top of the file like
typedef void (^ArrayEnumerationBlock) (id, NSUInteger, BOOL *);

Rather to write: void (^devowelizer) (id, NSUINteger, BOOL *);
you can   write: ArrayEnumerationBlock devowelizer;

If a block returns a value you can call that block variable like a function

double (^divinationBlock) (double, double) = ^(double k, double j) {
            return k/j;
}

Blocks are created and stored on the stack and will be destroyed (with the stack) when the function or method that created the block returns. To copy a block from the stack to the heap, you send it the copy message:
ArrayEnumerationBlock iVarSomething = [something copy]; (now the new block variable is a pointer to the block).Methods that takes blocks as arguments, are expected to copy blocks passed to them.
A heap-based block behaving like an object comes with some memory management issues:

#Source: The Big Nerd Ranch Guide (Objective C) - kindle version


  • external variables are captured by the block when the copy is made.
  • to avoid retain cycles declare a __weak pointer outside the block
  • variables captured by a block are constant within the block and you cannot change their values (you can still send the object messages that can change its contentsyou cannot modify the pointer itself).
  • if you want to change them you need to use __block otherwise you get compilation error.
__block int counter =0 ;
void (^counterBlock) () = ^ {counter++;};
...
counterBlock (); //Increments counter to 1
counterBlock ();//Increments counter to 2

No comments:

Post a Comment