ios developer tiny share-20161101

本文介绍了Objective-C中的Block语法,Block是一种语言级别的特性,允许创建独立的代码段,并将其作为值传递给方法或函数。Block类似于其他编程语言中的闭包或lambda表达式。文章详细解释了如何声明和使用Block,包括定义Block字面量、声明Block变量以及调用Block。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天开始新的一章,讲Block,C、C++、Objective-C都支持Block,就类似closures和lambdas。什么是Block,Block怎么用,今天开始讲。


下面是ios reference官方的讲解:


Working with Blocks

An Objective-C class defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods.

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages.

This chapter explains the syntax to declare and refer to blocks, and shows how to use blocks to simplify common tasks such as collection enumeration. For further information, see Blocks Programming Topics.



Block Syntax

The syntax to define a block literal uses the caret symbol (^), like this:

^{
	 NSLog(@"This is a block");
}
As with function and method definitions, the braces indicate the start and end of the block. In this example, the block doesn’t return any value, and doesn’t take any arguments.

In the same way that you can use a function pointer to refer to a C function, you can declare a variable to keep track of a block, like this:

void (^simpleBlock)(void);
If you’re not used to dealing with C function pointers, the syntax may seem a little unusual. This example declares a variable called simpleBlock to refer to a block that takes no arguments and doesn’t return a value, which means the variable can be assigned the block literal shown above, like this:

simpleBlock = ^{
	NSLog(@"This is a block");
};

This is just like any other variable assignment, so the statement must be terminated by a semi-colon after the closing brace. You can also combine the variable declaration and assignment:

void (^simpleBlock)(void) = ^{
	NSLog(@"This is a block");
};

Once you’ve declared and assigned a block variable, you can use it to invoke the block:

simpleBlock();


Note: If you attempt to invoke a block using an unassigned variable (a nil block variable), your app will crash.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值