int iVisen = 1000;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//int代码块
int mutl =7;
int (^visenBlock)(int) = ^(int num){return num *mutl;};
NSLog(@"%d",visenBlock(4));
//nsstring代码块
void (^visenPrintString)(NSString *str) = ^(NSString *str){
NSLog(@"print:%@", str);
};
visenPrintString(@"aaaa");
//代码用在字符串数组排序
NSArray *stringArray = [NSArray arrayWithObjects:@"abc 1", @"abc 21", @"abc 12",@"abc 13",@"abc 05",nil];
NSComparator visenSortBlock = ^(id string1,id string2){
return [string1 compare:string2];
};
NSArray *sortArray = [stringArray sortedArrayUsingComparator:visenSortBlock];
NSLog(@"sortArray:%@", sortArray);
//代码块的递归调用
//代码块想要递归调用,代码块变量必须是全局变量或者是静态变量,这样在程序启动的时候代码块变量就初始化了,可以递归调用
static void (^ const visenRecursionBlock)(int) = ^(int i){
if (i>0) {
NSLog(@"num: %d",i);
visenRecursionBlock(i-1);
};
};
visenRecursionBlock(3);
//在代码块中使用全局变量
void (^visenVariablesBlock)(void) =^(void){
iVisen ++;
NSLog(@"%d",iVisen);
};
visenVariablesBlock();
//在代码块中使用局部变量
//在代码块中改变局部变量编译不通过。怎么在代码块中改变局部变量呢?在局部变量前面加上关键字:__block
__block int iVisena= 1000;
void (^visenVariablesBlockB)(void) = ^(void){
iVisena++;
NSLog(@"local:%d", iVisena);
};
visenVariablesBlockB();
}