First, explain the block's structure with a graph:
Call the Block object variable as you call the function:
int result = Myblock (5); Result is 35.
Example 1: Using block delay method execution
/** * Deferred call method in the main thread * * @param block method principal block blocks * @param delay delayed seconds */-(void) Performblock: (void (^) (void)) block Afterde Lay: (nstimeinterval) delay{ int64_t delta = (int64_t) (1.0E9 * delay); Dispatch_after (Dispatch_time (Dispatch_time_now, Delta), Dispatch_get_main_queue (), block);}
Call Method:
[Self performblock:^{ //event handled in main thread } afterdelay:0.5];
Example two: Forcing the method to be called in the main thread:
/** * Force the method to be called in the main thread * * @param block method principal block block */-(void) Runonmainqueuewithblock: (void (^) (void)) block{ if (dispatch_ Get_current_queue () = = Dispatch_get_main_queue ()) { block (); } else { Dispatch_sync (Dispatch_get_main_queue (), block);} }
Call Method:
[Self runonmainqueuewithblock:^{ //In the main thread call method}];
Some examples of use of IOS block