Block Code in iOS

  1. @propery(copy, nonatomic) void( ^ updateStatus)(NSString * , NSString * );  
  2. self.updateStatus(@“papa”, @“Mamma”);  
  3. __weak HelloViewController * weakSelf = self;  
  4. XmppPresence * persence = [  
  5.     [xmppresence alloc] init];  
  6. presence.updateStatus = ^ (NSString * phone, NSString * status) {  
  7.     weakSelf.friendUserName = phone;  
  8. };  
  9. int( ^ howMany)(intint) = ^ (int a, int b) {  
  10.     return a + b;  
  11. };  
  12. void( ^ justAMessage)(NSString * ) = ^ (NSString * message) {  
  13.     NSLog(@  
  14.     "%@", message);  
  15. };  
  16. void( ^ xyz)(void);  
  17. xyz = ^ (void) {  
  18.     NSLog(@  
  19.     "What's up, Doc?");  
  20. };@interface ViewController()@property(nonatomic, strong) NSString * ( ^ blockAsAMemberVar)(void);@end  
  21. on didload.._blockAsAMemberVar = ^ (void) {  
  22.     return@  
  23.     "This block is declared as a member variable!";  
  24. };  
  25. int factor = 5;  
  26. int( ^ newResult)(void) = ^ (void) {  
  27.     return factor * 10;  
  28. };  
  29. NSLog(@  
  30. "%d", newResult());  
  31. NSDate * ( ^ today)(void);  
  32. today = ^ (void) {  
  33.     return [NSDate date];  
  34. };  
  35. NSLog(@  
  36. "%@", today());  
  37. float results = ^ (float value1, float value2, float value3) {  
  38.     return value1 * value2 * value3;  
  39. }(1.2, 3.4, 5.6);  
  40. NSLog(@  
  41. "%f", results);  

A completion handler is the way (technique) for implementing callback functionality using blocks.

When showing a modal view controller, if you want to handle something after the view controller has been presented: 

  1. - (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^)(void))completion NS_AVAILABLE_IOS(5_0);  
  2.   
  3.   
  4. [self presentViewController:viewController animated:YES completion:^{  
  5.   
  6.    NSLog(@"View Controller was presented...");  
  7.   
  8.    // Other code related to view controller presentation...  
  9.   
  10. }];  

Self method. 

  1. - (void)viewDidLoad    
  2. {  
  3.   
  4.    [self addNumber:5 withNumber:7 andCompletionHandler:^(int result) {  
  5.   
  6.       // We just log the result, no need to do anything else.  
  7.   
  8.       NSLog(@"The result is %d", result);  
  9.   
  10.    }];  
  11.   
  12. }  
  13.   
  14. -(void)addNumber:(int)number1 withNumber:(int)number2 andCompletionHandler:(void (^)(int result))completionHandler{  
  15.   
  16.    int result = number1 + number2;    
  17.    completionHandler(result);