Block Variables – blocks iOS
- The following rules apply to variables used within a block:
- Global variables are accessible, including static variables that exist within the enclosing lexical scope.
- Parameters passed to the block are accessible (just like parameters to a function).
- Stack (non-static) variables local to the enclosing lexical scope are captured as const variables.
- 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.
- Variables local to the enclosing lexical scope declared with the __block storage modifier are provided by reference and so are mutable.
- 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
- 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.
- 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.
- 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.
- 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.