Blocks Programming

https://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/_index.html
https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html
__block的例子:http://www.cnblogs.com/bandy/archive/2012/06/05/2536973.html
理解为java的内部类、C++嵌套类。
这个作用是体现了语言的封装性,多态,回调起来更隐蔽。

开源例子:UIAlertView-Blocks,使用代码块来回调。
https://github.com/jivadevoe/UIAlertView-Blocks


样子和函数指针像死了=。=
//定义
int (^Multiply)(int, int) = ^(int num1, int num2) {
    return num1 * num2;
};
//调用
int result = Multiply(7, 4); // result is 28


    char *myCharacters[3] = { "CC", "BB", "AA" };
    
    qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r) 
    {
        char *left = *(char **)l;
        char *right = *(char **)r;
        return strncmp(left, right, 1);
    });
        
    NSLog(@"%s", myCharacters[0]);
    NSLog(@"%s", myCharacters[1]);
    NSLog(@"%s", myCharacters[2]);


block作为方法的参数使用,传个函数指针给人家执行:
-(int)testBlockVar1:(int)var1 
               Var2:(int)var2 
              block:(int(^)(int a, int b))block
{
    return block(var1,var2);
}


- (IBAction)actionTest:(id)sender {
    
    
    int k = [self testBlockVar1:11 Var2:22 block:^(int c,int d)
             {
                 return c+d;
             }];
    
    NSLog(@"k = %d", k);
}





//原来的做法
- (void)viewDidLoad {
   [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(keyboardWillShow:)
        name:UIKeyboardWillShowNotification object:nil];
}
 
- (void)keyboardWillShow:(NSNotification *)notification {
    // Notification-handling code goes here.
}

//新的做法
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification
         object:nil queue:[NSOperationQueue mainQueue] 
usingBlock:^(NSNotification *notif) {
             // Notification-handling code goes here. 
    }];
}



Why Use Blocks?

One can discern a half-dozen or so use cases for blocks in framework methods:

Completion handlers
Notification handlers
Error handlers
Enumeration
View animation and transitions
Sorting

你可能感兴趣的:(programming)