[iOS] Important notes when working with blocks

Blocks iOS – Important notes when working with blocks

Blocks iOS

Block Variables – blocks iOS

  1. The following rules apply to variables used within a block:
  2. Global variables are accessible, including static variables that exist within the enclosing lexical scope.
  3. Parameters passed to the block are accessible (just like parameters to a function).
  4. Stack (non-static) variables local to the enclosing lexical scope are captured as const variables.
  5. Their values are taken at the point of the block expression within the program. In nested blocks, the value is captured from the nearest enclosing scope.
  6. Variables local to the enclosing lexical scope declared with the __block storage modifier are provided by reference and so are mutable.
  7. Local variables declared within the lexical scope of the block, which behave exactly like local variables in a function.

Block Ownership: Copy vs. Retain – blocks iOS

  1. All blocks have a valid class pointer, and appear to be Objective-C objects. According to the standard Objective-C memory management, to assume ownership of an object you must simply retain it. However, blocks differ from the standard Objective-C objects in at least one fundamental and very important way: blocks defined within a function are allocated on the stack, and will persist only until your function returns.
  2. This is why it is necessary to copy a block, rather than retain it: If the block is stack allocated, it must be copied to a heap allocation to persist beyond the lifetime of the current stack frame. Once copied, the block will be heap allocated and persist like any other standard Objective-C object.
  3. Thus, to ensure that you do not attempt to maintain ownership of a stack allocated block, you must always copy a block if you wish to reference it past the lifetime of your current function. As an optimization, if a block has already been copied to the heap copying will simply increment the block’s reference count.
  4. It should also be noted that there is one very real benefit to stack allocation of blocks: they are very cheap, and unless copied, require no allocations or cleanup.

More Details:

Apple Developer Site

Landon Fuller Blog

 

Dec, 15, 2014

  sticky

0