首页 > 代码库 > iOS Block浅析

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 OjbectNSString *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);    }

 

iOS Block浅析