简单的block

int multi = 7;
        
        int (^myBlock)(int) = ^(int num){
            return num * multi;
        };
        int result = myBlock(5);
        NSLog(@"结果是:%d",result);
//输出结果是:

结果是:35

void (^printBlock)(NSString *x);
        printBlock = ^(NSString* str)
        {
            NSLog(@"print:%@", str);
        };
        printBlock(@"这是个block!");
//输出结果:

print:这是个block!

//字符串数组排序

NSArray *strArr = [NSArray arrayWithObjects:@"abc 02",@"abc 1",@"abc 2", @"abc 21", @"abc 12",@"abc 13",@"abc 15",nil];
        NSComparator sortBlock = ^(id str1, id str2)
        {
            return [str1 compare:str2];
        };
        NSArray *Arr = [strArr sortedArrayUsingComparator:sortBlock];
        NSLog(@"这个数组是:%@", Arr);
//输出结果:

这个数组是:(
    "abc 02",
    "abc 1",
    "abc 12",
    "abc 13",
    "abc 15",
    "abc 2",
    "abc 21"
)
//很神奇,竟然默认为10 和 20;如果不加0的话。

static void (^ const blocks)(int) = ^(int i)
        {
            if (i > 0) {
                
                NSLog(@"数字:%d", i);
                blocks(i - 2);
//                NSLog(@"shuzi:%d",i);
//                blocks(i + 2);
            }
        };
        blocks(10);
        
//输出的是 10 8  6 4 2

注:千万不能往上加!!

int num = 500;
        int main(int argc, const char * argv[])
        {
            @autoreleasepool {
                void(^block)(void) = ^(void)
                {
                    num++;
                    NSLog(@"输出:%d", num);
                };
                block();
                NSLog(@"输出:%d", num);
            }
            return 0;  
        }
//运行结果:

输出:501

输出:501

//在代码块中改变局部变量编译不通过,会报错。要在代码块中改变局部变量,需要在局部变量前面加上关键字:__block

__block int local = 500;
        void(^block)(void) = ^(void)
        {
            local++;
            NSLog(@"local:%d", local);
        };
        block();  
        NSLog(@"local:%d", local);
//注:两个下划线_+_合成的__block

上一篇:【目录】Python学习笔记


下一篇:Bitmap工具类