2. Blocks
• What is a block ?
• Who is the block owner ?
• What is retained by the block ?
3. What is a block?
• An object
• It can capture values from the Enclosing Scope
• It can be used for callback
4. Who is the owner?
• Since it’s an object, the owner is the last object
with reference to it.
• It can be shared between multiple objects.
• It can change owner many time.
5. What is retained by block
• Value from the Enclosing Scope used inside.
• Is own scope value.
• Parameters
6. Memory Variables
• __blocks is used to share storage.
• You will typically use it when you need update a variable inside the
block.
• __weak is used to send reference without maintain
• You need use it when you use block as a callback and you don’t want
the variable retained by owner of block
• __strong is the default memory variable
• You don’t need add it but it can be use like ‘a flag’
7. __block sample
__block int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger);
anInteger = 100;
};
testBlock();
NSLog(@"Value of original variable is now: %i",
anInteger);
!
Integer is: 42
Value of original variable is now: 100
8. __strong sample
self.block = ^{
[self doSomething];
};
!
// capturing a strong reference to self
// creates a strong reference cycle
9. __weak sample
typeof(self) __weak weakSelf = self;
self.block = ^{
[weakSelf doSomething];
}
!
// capture the weak reference
// to avoid the reference cycle