Blocks & Memory

339 views

Published on

Support for presentation about blocks and memory.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
339
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Blocks & Memory

  1. 1. Blocks & Memory A specific management.
  2. 2. Blocks • What is a block ? • Who is the block owner ? • What is retained by the block ?
  3. 3. What is a block? • An object • It can capture values from the Enclosing Scope • It can be used for callback
  4. 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. 5. What is retained by block • Value from the Enclosing Scope used inside. • Is own scope value. • Parameters
  6. 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. 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. 8. __strong sample self.block = ^{ [self doSomething]; }; ! // capturing a strong reference to self // creates a strong reference cycle
  9. 9. __weak sample typeof(self) __weak weakSelf = self; self.block = ^{ [weakSelf doSomething]; } ! // capture the weak reference // to avoid the reference cycle
  10. 10. Demo

×