#import "ViewController.h"
@interface ViewController ()
@end
int num = 100;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
/**
Block
什麼是 Block? P201
Block 是 iOS4.0+ 和 Mac OS X 10.6+ 引進的對 C 語言的擴展,用來實現匿名函數的特徵
block 是 C 級別的匿名函數塊 和 C語言的函數指針很像,在 iOS4.0 之後就開始支持 block
在 iOS 開發中什麼情況使用 block?
1.代碼的封裝
2.併發任務的執行
3.回調
block 塊語法:
返回值類型(^代碼塊名字)(參數列表) = ^(參數列表){代碼塊的行爲主體};
*/
//block 塊的聲明
int (^Sum)(int n1,int n2);
//block 塊的實現
Sum = ^(int n1, int n2){
return n1 + n2;
};
//block 塊的調用
int result = Sum(1,3);
NSLog(@"result = %d",result);
//block 塊的聲明
int (^Sum2)(int n1,int n2,int n3);
//block 塊的實現
Sum2 =^(int n1,int n2,int n3){
int max = n1;
if (n1 < n2) {
max = n2;
} else {
max = n3;
}
return max;
};
//block 塊的調用
int max = Sum2(1,3,2);
NSLog(@"max = %d",max);
//無返回值類型
//聲明
void (^jack)(NSString *string);
//實現
jack =^(NSString *string){
NSLog(@"%@",string);
};
jack(@"Rick");
//在代碼塊中使用全局變量 和 局部變量
//聲明和實現 全局變量
void(^myBlockOne)() = ^() {
num++;
NSLog(@"num =%d",num);
};
//調用
myBlockOne();
__block int numTwo = 100;
void(^myBlockTwo)() = ^() {
// numTwo++; //意味着局部變量可以使用,但不能改變它,那如何在中代碼塊中改變局部變量呢?子啊局部變量前面加上關鍵字:__block ,注意這裏的 block 關鍵字前面是兩個下劃線。
numTwo++;
NSLog(@"numTwo = %d",numTwo);
};
myBlockTwo();
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end