Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do blocks differ from normal methods and functions in Objective-C?

What is the advantage of using blocks over normal methods and functions in Objective-C? I've read the documentation, but I can't find specific uses of blocks instead of other language features.

I'm sure that I've missed something, so could someone explain the advantages of blocks in a simpler way than the existing documentation?

like image 773
Ajay Pandey Avatar asked Aug 23 '10 09:08

Ajay Pandey


People also ask

What is the purpose of block in Objective-C?

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary .

How do you write blocks in Objective-C?

^blockName: Always remember that the block name is preceded by the ^ symbol. The block name can be any string you like, just like you name any other variable or method. Remember that both the ^ and the block name are enclosed in parentheses ().

What is Objective-C blocks called in Swift?

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.


1 Answers

Blocks are a way of wrapping up a piece of code and effectively storing it for later use. A block is commonly used in place of a call back function. Newer APIs in the iPhone SDK use blocks this way. The API will take a "block" of code that it will run on completion.

It saves you having to create your own threads and maintain the state of each thread, manage locks, setup autorelease pools etc.

When used with the Grand Central Dispatch (GCD) API blocks can be run on queues and entire portions of code can be made to run asynchronously with very little effort, but still keeping the robustness that is required for multithreaded code.

like image 109
Jasarien Avatar answered Sep 23 '22 20:09

Jasarien