您的位置:首页 > 移动开发 > IOS开发

IOS block编程指南 4 声明和创建blocks

2015-03-16 17:16 330 查看



DeclaringandCreatingBlocks(声明和创建blocks)


DeclaringaBlockReference(声明一个block引用)

Blockvariablesholdreferencestoblocks.Youdeclarethemusingsyntaxsimilartothatyouusetodeclareapointertoafunction,exceptthatyouuse
^
instead
of
*
.TheblocktypefullyinteroperateswiththerestoftheCtypesystem.Thefollowingareallvalidblockvariabledeclarations:
block变量维持了一个对block的引用。你声明block使用了和声明函数指针相同的语法,除了你使用“^”代替了“*”之外。block类型可以和全部C类型系统相互操作。下列都是block变量的声明:

void(^blockReturningVoidWithVoidArgument)(void);

int(^blockReturningIntWithIntAndCharArguments)(int,char);

void(^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);

Blocksalsosupportvariadic(
...
)arguments.Ablockthattakesnoarguments
mustspecify
void
intheargumentlist.
Blocksaredesignedtobefullytypesafebygivingthecompilerafullsetofmetadatatousetovalidateuseofblocks,parameterspassedtoblocks,andassignmentofthereturnvalue.Youcan
castablockreferencetoapointerofarbitrarytypeandviceversa.Youcannot,however,dereferenceablockreferenceviathepointerdereferenceoperator(
*
)—thus
ablock'ssizecannotbecomputedatcompiletime.
Youcanalsocreatetypesforblocks—doingsoisgenerallyconsideredtobebestpracticewhenyouuseablockwithagivensignatureinmultipleplaces:
blocks也支持可变参数。一个没有参数的block必须在参数列表中指定void。

blocks被设计成对编译器的完全安全类型,它有一套完整的数据源设置来检测block的合法性,通过传给blocks参数,来分配返回值。你可以给block创建任意的指针类型,反之亦然(PS:这句话,翻译有疑问)。尽管如此,你不能通过解引用操作符(*)来解引用一个block——因为这样在编译的时候无法计算block的大小。
你也可以创建block作为类型,当你要在多个地方使用同一block签名的block的时候,这是通常情况下最好的方法。

typedeffloat(^MyBlockType)(float,float);


MyBlockTypemyFirstBlock=//...;

MyBlockTypemySecondBlock=//...;


CreatingaBlock(创建一个block)

Youusethe
^
operatortoindicatethebeginningofablockliteralexpression.Itmaybefollowed
byanargumentlistcontainedwithin
()
.Thebodyoftheblockiscontainedwithin
{}
.
Thefollowingexampledefinesasimpleblockandassignsittoapreviouslydeclaredvariable(
oneFrom
)—heretheblockisfollowedbythenormal
;
that
endsaCstatement.
你使用^操作指示一个block表达的开始。也许还会有一个()包裹的参数列表。block的主体包含在{}中。下面的例子定义了一个简单的block分配给一个已经存在的变量(oneFrom)——这里的block是正常的,以C语言做结。

float(^oneFrom)(float);


oneFrom=^(floataFloat){

floatresult=aFloat-1.0;

returnresult;

};

Ifyoudon’texplicitlydeclarethereturnvalueofablockexpression,itcanbeautomaticallyinferredfromthecontentsoftheblock.Ifthereturntypeisinferredandtheparameterlistis
void
,
thenyoucanomitthe
(void)
parameterlistaswell.Iforwhenmultiplereturnstatementsarepresent,theymustexactlymatch(usingcasting
ifnecessary).
如果你没有明确的声明block表达式的返回值,系统可以根据block的内容推断。如果返回类型推断好,且参数列表为空,然后你也可以忽略参数列表。如果需要很多返回值,他们需要寄去匹配(如果必要可以进行类型转换)。


GlobalBlocks(全局block)

Atafilelevel,youcanuseablockasagloballiteral:
在文件层面,你可以把block作为全局变量。

#import<stdio.h>


intGlobalInt=0;

int(^getGlobalInt)(void)=^{returnGlobalInt;};

NextPrevious

本文原创,转载请注明出处:http://blog.csdn.net/zhenggaoxing/article/details/44308855
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: