iPhone Development

Just another iPhone Blog

Tag Archives: GCD

Why I like Blocks?

In my last post here , I wrote about the syntactical difference between the Blocks and the C Funtion pointers. In this post I share my first hand experience on Blocks and how it changed my programming style and thinking, especially if you are not from Java / Javascript world.

 

In simple terms, Blocks are tiny independent code blocks that could be executed on its own. How did Blocks saved me? Lets take below code snippet as an example:

 

[imageDownloader downloadHUGEImage: ^(UIImage* newImage){

    [self createThumbNailForImage:(UIImage * newImage)];

}]

 

v/s

 

[imageDownloader setDownloadDelegate: self ];

[imageDownloader downloadHUGEImage];

..

..

.

 

– (void)imageDownloader:(BBImageDownloader*)downloader didDownloadImage:(UIImage*)image

{

    [self createThumbNailForImage:(UIImage * newImage)];

}

 

Advantage #1: It added more readability to my code:

Everyone would know what we are exactly doing after downloading an image, where as with delegate pattern, one has to jump to definition of the delegate methods, which sometimes resides in multiple files, by then you would lose the trace of the initial method.

 

Advantage #2: Eliminates Delegate Pattern

The same reason as above, With Blocks, you will no more have to spend your time in retain cycle which is more common mistake made by programmer when using delegate pattern in Objective-C, (although blocks do produce retain cycles, but they are easy to detect   )

 

 

Advantage #3: Save more context info variables.

Lets take an example of usage of beginAnimation: method on UIView in Pre-Block Era.

int state_before_animation = 0

[UIView beginAnimations:@” ” contextInfo:& state_before_animation]

 

..

 

..

 

– (void)animations:(NSString*)animation didFinish:(BOOL)finish contextInfo:(void*)contextInfo

{

    //do some\

int *state_before_animation = (int*)contextInfo

//change state depending upon state_before_animation

}

 

 

– During the execution time between start of animation  and completion of animation, we lose the scope of local variables that were available at the start. This made the necessity of carrying these variables in the form of contextInfo

 

– It increases the burden of maintaining the integrity of the contextInfo variable during this time, it travels between different modules and sometimes b/w the third party libraries. 

 

With blocks, it makes much more simpler to write:

 

int state_before_animation =0

[UIView animateWithDuration:0.9 beforeAnimation:^{

 

}

afterAnimation:^{

   //do something depending upon state_before_animation

}

];

 

 Isn’t it decreases your development time?

 

Happy Coding 🙂