I want to use blocks in my application, but I don’t really know anything about blocks. Can anyone explain how and why I should use blocks in my code?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Blocks are closures (or lambda functions, however you like to call them). Their purpose is that using blocks, the programmer doesn’t have to create named functions in the global scope or provide a target-action callback, instead he/she can create an unnamed, local “function” which can access the variables in its enclosing scope and easily perform actions.
For example, when you want to e. g. dispatch an asynchronous operation, such an animation for views, without blocks, and you wanted to be notified of the competion, you had to write:
This is a lot of code, furthermore it implies the presence of a valid
selfpointer – that might not always be available (I experience such a thing when I was developing MobileSubstrate-tweaks). So, instead of this, you can use blocks from iOS 4.0 and onwards:Or, for example, loading online resources with NSURLConnection… B. b. (Before Blocks):
A. B. (Anno Blocks):
Much easier, cleaner and shorter.