Block in iOS (2)

来源:互联网 发布:linux视频播放器安装 编辑:程序博客网 时间:2024/05/22 07:43

上次介绍了block的基本概念,以及在iOS开发中我们一般怎么使用它,那这次重点介绍block和变量之间的使用规范,根据苹果在Apple document中的描述,block中的变量一般的使用得注意一下几个方面:

1、全局的变量是可以在block中访问的,包括静态变量;

2、block自带的参数可以访问,这个就跟函数使用它自己的参数是一样的;

3、栈变量在block中的使用按照常量对待;

     下面的是一个例子:

    int x = 123;

    

    

    void (^printXAndY)(int) = ^(int y) {

        printf("%d %d\n", x, y);

    };

    

    

    printXAndY(456);                  // prints: 123 456

 

另外的一个错误使用的例子如下:

 

    int x = 123;

    

    

    void (^printXAndY)(int) = ^(int y) {

        x = x + y;                     // Error with "Variable is not assignable

        

        x ++;

        

        y = x ++;

        

        printf("%d %d\n", x, y);

        

    };

 

4、以_block定义的局部变量在block中允许被修改,这种情况下,它的使用和函数中的变量一样。

    _block int x = 123;   //x lives in block storage

    

    

    void (^printXAndY)(int) = ^(int y) {

        

        x = x + y;

        

        printf("%d %d\n", x, y);

        

    };

    

    

    printXAndY(456);             // prints: 579 456

    

    // x is now 579


5、对于全局变量,常量不允许在block中进行修改,否则会跑出来一个错误“Read-only variable is not assignable“,但是对于类似int GlobleInt1 = 1的全局变量声明,它是可以在block中进行更改的,比如下面的代码:

    void (^addX)(int) = ^(int x) {

                

        GlobleInt1 = x ;

        

        NSLog(@"GlobalInt = %d"GlobleInt1);//Output: GlobalInt = 100

GlobleInt1 ++;


    };

    

    NSLog(@"GlobalInt = %d"GlobleInt1);//Output: GlobalInt = 1

    

    addX(100);

    

    NSLog(@"GlobalInt = %d"GlobleInt1);//Output: GlobalInt = 101


6、对于Block,还有一个有意思的地方,请看下面的代码:

int value = 10;


int(^add)(int) = ^(int valueOne)

{

    return value + valueOne;

};


value = 20;


NSLog(@"Result: %d", add(3));


大家猜猜输出是多少?有多少人认为是23的?答案是13,为什么呢,因为Block的调用,参数取的是它定义时刻的value。再比如以下的代码:

int value = 10;


value = 15;


value = 33;


int(^add)(int) = ^(int valueOne)

{

    return value + valueOne;

};


value = 20;


NSLog(@"Result: %d", add(3));


它的输出为33 + 3 = 36,那么如果我们设定value为__block的呢?看如下的代码:

__block int value = 10;


value = 15;


value = 33;


int(^add)(int) = ^(int valueOne)

{

    return value + valueOne;

};


value = 20;


NSLog(@"Result: %d", add(3));


它的输出为23.

Block的生命周期和函数的类似,一开始Block都是放在stack里面的,换句话说就是它的生命周期随着method或function结束就会被回收。
0 0