iOS Interview Prep 3 — Blocks and Closures
The purpose of this interview preparation series is to assist you in quickly refining your interview skills and thoroughly preparing for the typical questions asked during an iOS interview. If you find it useful, please leave a comment or tap the like button.
Overview
Closure or block is a unit of code that can be passed around and executed at a later time. They behave very similar to functions, but they are more flexible and powerful. Because they can be passed as arguments to functions, stored in variables, and even used as return values.
Interview Questions
- Can blocks capture variables from their surrounding scope? Explain with an example.
- How can you avoid creating a strong reference cycle when using a closure or block?
- In what situations would you use the
weak
keyword, and in what situations would you use theunowned
keyword? - What is the purpose of the
__block
modifier in Objective-C blocks? Explain with an example.
How block works
Blocks are implemented as Objective-C objects of type NSBlock
they are just structs with an isa
pointer. Literals are directly translated into structs by the compiler. Each block object contains a pointer to…