Skip to main content

Posts

Showing posts from September, 2015

Blocks are Objective-C Objects !!!

Blocks Blocks are executable code just like a function.  It can be written inside a function or we can store the reference in a variable and call it later.  But wait a minute these all functionality we can achieve by function pointer and functions.  Then what is so special about blocks? Let first go through how we can define blocks. int (^sum)( int , int ) = ^( int number1, int number2){ return number1+number2; }; The above block can be used to find the sum of two numbers.  If we recall the function pointer in c then it is very much similar to above: int sumFunction ( int number1, int number2){ return number1+number2; } int (*sum) ( int , int ) = sumFunction; //Function Pointer *sum Then Why we need Blocks if we already have Function pointer?  1) B locks can capture variables from the enclosing scope by simply referring to them within the block. How ? Let see the next Section 2)  Blocks...

dispatch_async vs dispatch_sync

GCD: A library to provide support for concurrent code execution on multicore hardware in iOS. It provides an easier mechanism to access multi-thread environment without taking the overhead of lock and unlock shared data, create a thread and perform a task like that. If we use  NSThread or pthread in the application then we need to take care of so much point. Like if I need to execute 10 tasks concurrently in my application. How much thread pool I require, how to synchronise two tasks while using threads. It provides methods to add a task in a queue. 1) Dispatch Async 2) Dispatch Sync  Dispatch Async: This method is used to add a block for asynchronous execution and return immediately. If you used this method to add a block then it will return immediately and does not wait for execution of the block. If you do not want to wait for the execution of the block then you can use this method to add operation in a dispatch queue. - ( void ) performMyTask{ ...