zoukankan      html  css  js  c++  java
  • iOS学习之代码块(Block)

    代码块(Block)

    (1)主要作用:将一段代码保存起来,在需要的地方调用即可。

    (2)全局变量在代码块中的使用

    全局变量可以在代码块中使用,同时也可以被改变,代码片段如下:

    1 int local = 1;//注意:全局变量
    2 void (^block0)(void) = ^(void){
    3     local ++;
    4     NSLog(@"local = %d",local);
    5 };    
    6 block0();
    7 NSLog(@"外部 local = %d",local);

    结果为:local = 2;

    外部 local = 2;

    (3)局部变量在代码块中的使用

    **一般的局部变量只能在代码块中使用,但不能被改变(此时无法通过编译),代码片段如下:

    1 int n = 1000;//局部变量
    2 void (^block1)(void) = ^(void){
    3 //  n++;
    4     NSLog(@"float1 = %d",n);
    5 };
    6 block1();
    7 NSLog(@"float2 = %d",n);

    结果为:float1 = 1000

    float2 = 1000

    **将局部变量声明为__block时,不仅可以在代码块中使用,同时也可以被改变。代码片段如下:

    1 __block int j = 200;//声明为__block变量
    2 void (^block2)(void) = ^(void){
    3     j++;
    4     NSLog(@"块变量 = %d",j);
    5 };
    6 block2();
    7 NSLog(@"快变量2 = %d",j);

    结果为:块变量 = 201

    快变量2 = 201

    (4)代码块作为方法参数使用

    自定义类:

    首先BlockClasss.h类:

     1 #import <Foundation/Foundation.h>
     2 
     3 @interface BlockClasss : NSObject
     4 
     5 //声明int型变量
     6 @property (nonatomic,assign)int result;
     7 @property (nonatomic,assign)int result2;
     8 
     9 - (int)result:(int (^)(int))block;
    10 
    11 - (BlockClasss *(^)(int value))add;
    12 @end

    然后BlockClasss.m的实现:

     1 #import "BlockClasss.h"
     2 
     3 @implementation BlockClasss
     4 - (int)result:(int (^)(int))block{
     5     _result = block(_result);
     6     return _result;
     7 }
     8 
     9 - (BlockClasss *(^)(int))add{
    10     return ^BlockClasss *(int value){
    11         _result2 += value;
    12         return self;
    13     };
    14 }
    15 @end

    代码块作为方法参数的使用代码:

    1 BlockClasss *bl = [[BlockClasss alloc]init];
    2 [bl result:^int(int result) {
    3     result += 10;
    4     result *= 2;
    5     return  result;
    6 }];
    7 NSLog(@"result = %d",bl.result);

    结果为:result = 20

    (5)代码块作为方法返回值使用:

    1 BlockClasss *bl2 = [[BlockClasss alloc]init];
    2 bl2.add(100).add(200);
    3 NSLog(@"结果 ^=%d",bl2.result2);

    打印结果为:结果 ^=300

    (6)避免循环引用

    在代码块中不能使用self或者_XXX,以免发生循环引用。最好是将self在外部定义为__weak属性,然后再去使用。

    例如:

    1 __weak self weakSelf = self;
    2 _block = ^{
    3     NSLog(weakSelf.result);
    4 };
  • 相关阅读:
    如何自动生成参考文献格式
    VS2010+OpenCV 项目生成EXE文件如何在其他电脑上直接运行
    从多核CPU Cache一致性的应用到分布式系统一致性的概念迁移
    【译】为什么永远都不要使用MongoDB Why You Should Never Use MongoDB
    团队技能提升的二三事儿
    从微信朋友圈的评论可见性,谈因果一致性在分布式系统中的应用
    我所认为的软件可靠性的三重境界
    Redis核心原理与实践--事务实践与源码分析
    Redis核心原理与实践--Redis启动过程源码分析
    选择SaaS平台的那些事
  • 原文地址:https://www.cnblogs.com/calence/p/6083902.html
Copyright © 2011-2022 走看看