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
}
}