---------------
main.m
---------------
#import
<Foundation/Foundation.h>
int
main()
{
// 定义不带参数、无返回值的块
void (^printStr)( void ) = ^( void )
{
NSLog( @" 我正在开始学习 Objective-C 的块 " );
{
// 定义不带参数、无返回值的块
void (^printStr)( void ) = ^( void )
{
NSLog( @" 我正在开始学习 Objective-C 的块 " );
};
printStr();
//
定义带参数、有返回值的块
double (^hypot)( double , double ) =
^( double num1, double num2)
{
return sqrt(num1 * num1 + num2 * num2);
double (^hypot)( double , double ) =
^( double num1, double num2)
{
return sqrt(num1 * num1 + num2 * num2);
};
NSLog(
@"%g"
, hypot(
3
,
4
));
//
也可以先只定义块变量:定义带参数、无返回值的块
void (^print)(NSString*);
// 再将块赋给指定的块变量
print = ^(NSString* info)
{
NSLog( @"info 参数为: %@" , info);
void (^print)(NSString*);
// 再将块赋给指定的块变量
print = ^(NSString* info)
{
NSLog( @"info 参数为: %@" , info);
};
print(
@"
疯狂
iOS
讲义
"
);
}
一、编写本节代码的具体步骤:
1.参照003节的代码编写步骤。
二、本节代码涉及到的知识点:
1.block是一种数据类型。
2.block的作用:用来保存一段代码。
3.block的标志:^ 。
4.block与函数的共同点:①保存一段代码 ②有返回值 ③有形参 ④调用方法一样
5.block的定义方式跟指向函数的指针很像,详情请参考第79节。