// 定义一个Block Object,返回值:NSString;别名:intToString;参数:NSUInteger。
NSString* (^intToString)(NSUInteger) = ^(NSUInteger paramInteger){
};
// 调用我们定义的Block Ojbect
NSString *string = intToString(10);
NSLog(@"string = %@", string);
typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{
}
typedef NSString* (^IntToStringConverter)(NSUInteger paramInteger);
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(IntToStringConverter)paramBlockObject{
}
- (void) doTheConversion{
}
[self doTheConversion];
什么是内联Block?
我的理解是,写在方法内部的,编译器在编译阶段无法知道要调用的具体Block内容。
就像上边的例子:
独立Block:在编译阶段,已经就定义好了Block方法:
//
NSString* (^intToString)(NSUInteger) = ^(NSUInteger
};
内联Block:在编译阶段,编译器并不知道所关联的Block是什么。
因为它是在调用doTheConversion方法时,临时分配的(inlineConverter)。红色块。
- (void) doTheConversion{
}
同理,就相当于:
- (void) doTheConversion{
}
是啊,很多iOS中的方法,用的都是这种方式!对用的就是内联Block!!!
原来如此啊!
先mark到这里吧!
下一步,我们来了解一下,关于Block变量的一些东西!
Block 的变量
1.独立Block 变量的操作。
定义Block:
void (^independentBlockObject)(void) = ^(void){
};
调用:
independentBlockObject();
输出:
2013-03-26 20:13:50.144 DemoVideo[20505:707] local integer = 10
2013-03-26 20:13:50.147 DemoVideo[20505:707] local integer = 20
2.内联Block 变量的操作。
我们知道Object-C中已经有很多用Block作为参数的函数。该Block参数,作为内联Block调用。
于是,就用一个数组比较的方法:
定义:
- (void) simpleMethod{
}
调用:
[self simpleMethod];
输出:
Printing description of sortedArray:
<__NSArrayI 0x1f56d430>(
100,
150,
200
)
Printing description of array:
<__NSArrayM 0x1f585ed0>(
100,
200,
150
)
我们不用关心,sortedArrayUsingComparat
可见:独立Block可以在内部定义变量,访问变量,修改变量!
Block可以读写自己内部的变量,那么对于外部变量,有如何呢 ?
不着急,我们先来归纳一下用于测试的相关代码:
定义Block签名
typedef NSString* (^UserMyBlockFun)(NSUInteger paramInteger);
定义Block为参数的函数
- (NSString *)convertIntToString:(NSUInteger)paramInteger usingBlockObject:(UserMyBlockFun)paramBlockObject{
}
定义调用函数:
- (void) doTheConversion{
//
}
可见,对于外部普通变量,Block只有读取的权限。
但是,从一个错误:Variable is not assignable(missing __block type specifier)中,也许我们可以知道,
如果,要对外部变量具有写权限,那么就要在变量前,加上“__block”
这样,就可以读写outsideVariable变量了。
内联Block可以直接访问self;但是,独立Block不能直接访问self,替代方式为,将self作为参数,传递给Block。
如:
// 独立Block
void (^correctBlockObject)(id) = ^(id self){
};
- (void) callCorrectBlockObject{
}
有一点非常重要:
内联Block,调用的外部变量,使用的是复制方式。
运行一下,查看输出就知道了:
- (void) scopeTest{
}
如果要使用引用方式,那么就要在变量前加上“
调用 Block
关于内联Block,因为其就是写在方法内的,所以,调用起来相对方便。就像iOS中的API,有很多方法,使用了内联Block方式。
关于独立Block,主要使用C语言的函数调用方式。
用例子来说明吧。
1.调用Block
// 定义Block
void (^simpleBlock)(NSString *) = ^(NSString *theParam){
};
// 调用Block
- (void) callSimpleBlock{
}
2.嵌套调用
// 定义内层Block
NSString *(^trimString)(NSString *) = ^(NSString *inputString){
};
// 定义外层Block
NSString *(^trimWithOtherBlock)(NSString *) = ^(NSString *inputString){
};
// 调用方法
- (void) callTrimBlock{
}
希望对你有所帮助!