zoukankan      html  css  js  c++  java
  • iOS Block浅析

    Block 的使用有两种:1.独立Block 。2.内联Block 。
     
    《一》独立Block 使用方式
     
    一、定义一个Block Object,并调用。
     
    1.定义
     
    // 定义一个Block Object,返回值:NSString;别名:intToString;参数:NSUInteger。
    
    NSString* (^intToString)(NSUInteger) = ^(NSUInteger paramInteger){
    
        NSString *result = [NSString stringWithFormat:@"%lu",(unsignedlong)paramInteger];
    
        return result;
    
    };
     
    2.调用
     
    // 调用我们定义的Block Ojbect
    
    NSString *string = intToString(10);
    
    NSLog(@"string = %@", string);
     
    二、将Block Object 当作参数,在方法之间传递,调用。
     
    有时候,我们希望将定义的Block Object作为函数的参数使用,就像其他的数据类型一样。
     
    1.为Block Object 定义签名
     
    typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
    这就告诉,编译器,我们定义了一个签名(别名)为IntToStringConverter 的Block Object。这个Block返回值为:NSString;参数为:NSUInteger。
     
    2.定义使用Block为参数的函数
     
    - (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{
    
        return paramBlockObject(paramInteger);
    
    }
    这一步,很简单,我们将前面定义的Block作为了一种类型。这种类型为:IntToStringConverter
     
    3.调用使用Block为参数的方法
     
     NSString *result = [self convertIntToString:123 usingBlockObject:intToString];
    
        NSLog(@"result = %@", result);
    调用时,123,和intToString可理解为实参。
     
    《二》内联Block 使用方式
     
    在此之前,让我们梳理一下需要的代码:
     
    1.定义
    typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
    2.用Block作为参数的函数
    - (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{
    
        return paramBlockObject(paramInteger);
    
    }
    3.内联调用
    - (void) doTheConversion{
    
        IntToStringConverter inlineConverter = ^(NSUInteger paramInteger){
    
            NSString *result = [NSString stringWithFormat:@"%lu", (unsignedlong)paramInteger];
    
            return result;
    
        };
    
        
    
        NSString *result = [self convertIntToString:123usingBlockObject:inlineConverter];
    
        NSLog(@"result = %@", result);
    
        
    
    }
  • 相关阅读:
    pythonldap 简单试用
    shell 将文件名读入数组
    pytest命令行传入自定义的参数到测试文件中
    Python实现在不同Linux主机之间拷贝文件
    使用minio搭建私有化对象存储服务
    CPU/GPU/NPU
    pytest 内置和自定义marker
    安装SQLite3引发的库问题
    C标准库——程序员等级
    这样还弄不死指针?
  • 原文地址:https://www.cnblogs.com/weiboyuan/p/4195902.html
Copyright © 2011-2022 走看看