Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the real advantages of using blocks in Objective-C? [closed]

Tags:

objective-c

I have learned about blocks in ObjC, the syntax is clear and simple. I can read “blocks are a great feature, the syntax is...” almost everywhere. However, I miss the real advantages of their using.

Maybe it is a silly question - I have just started with ObjC, but what are the real advantages of blocks over a “traditional” approach? Can anybody give me some brief and clear explanation?

like image 275
vitakot Avatar asked Feb 12 '12 17:02

vitakot


2 Answers

Anything you can do with blocks, you can do without them. But they provide a great way to simplify your code and make things cleaner. For example, let's say you have a URL connection and want to wait for the result. Two popular approaches are to provide a delegate callback or use a block. I'll use the fictitious URLConnection class as an example.

URLConnection* someConnection = [[[URLConnection alloc] initWithURL:someURL] autorelease];
someConnection.delegate = self;
[someConnection start];

Then somewhere else in your class

- (void)connection:(URLConnection)connection didFinishWithData:(NSData*)
{
    // Do something with the data
}

By contrast, when you use a block, you can embed the code that gets called right where you create the connection.

URLConnection* someConnection = [[[URLConnection alloc] initWithURL:someURL] autorelease];
someConnection.successBlock = ^(NSData*)data {
    // Do something with the data
};
[someConnection start];

In addition, let's say you have multiple connections in your class all using the same delegate. Now you have to differentiate between them in your delegate method. This can get complicated the more of them you have. And with a block, you can assign a unique block per URL connection.

- (void)connection:(URLConnection)connection didFinishWithData:(NSData*)
{
    if(connection == self.connection1)
    {
        // Do something with the data from connection1
    }
    if(connection == self.connection2)
    {
        // Do something with the data from connection2
    }
    if(connection == self.connection3)
    {
        // Do something with the data from connection3
    }
}
like image 120
DHamrick Avatar answered Nov 07 '22 06:11

DHamrick


Define "traditional approach"?

Personally, it's nicer see a block, as you can see what the response is going to be to an operation inline and grouped with the operation itself.

The "traditional" callback (that's what I'm assuming you mean) way, will result in having to jump somewhere else in the code to see how something will be handled and jumping back, rather than just reading everything "together".

like image 20
twilson Avatar answered Nov 07 '22 06:11

twilson