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

IOS Dev Intro - Blocks Programming Series 03

2016-06-12 10:21 447 查看
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Blocks/Articles/bxDeclaringCreating.html#//apple_ref/doc/uid/TP40007502-CH4-SW1


DeclaringandCreatingBlocks


DeclaringaBlockReference

Blockvariablesholdreferencestoblocks.Youdeclarethemusingsyntaxsimilartothatyouusetodeclareapointertoafunction,exceptthatyouuse 
^
 instead
of 
*
.TheblocktypefullyinteroperateswiththerestoftheCtypesystem.Thefollowingareallvalidblockvariabledeclarations:

void(^blockReturningVoidWithVoidArgument)(void);

int(^blockReturningIntWithIntAndCharArguments)(int,char);

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

Blocksalsosupportvariadic(
...
)arguments.Ablockthattakesnoargumentsmustspecify 
void
 in
theargumentlist.
Blocksaredesignedtobefullytypesafebygivingthecompilerafullsetofmetadatatousetovalidateuseofblocks,parameterspassedtoblocks,andassignmentofthereturnvalue.Youcancastablock
referencetoapointerofarbitrarytypeandviceversa.Youcannot,however,dereferenceablockreferenceviathepointerdereferenceoperator(
*
)—thus
ablock'ssizecannotbecomputedatcompiletime.
Youcanalsocreatetypesforblocks—doingsoisgenerallyconsideredtobebestpracticewhenyouuseablockwithagivensignatureinmultipleplaces:

typedeffloat(^MyBlockType)(float,float);


MyBlockTypemyFirstBlock=//...;

MyBlockTypemySecondBlock=//...;


CreatingaBlock

Youusethe 
^
 operatortoindicatethebeginningofablockliteralexpression.Itmaybefollowedbyan
argumentlistcontainedwithin 
()
.Thebodyoftheblockiscontainedwithin 
{}
.
Thefollowingexampledefinesasimpleblockandassignsittoapreviouslydeclaredvariable(
oneFrom
)—heretheblockisfollowedbythenormal 
;
 that
endsaCstatement.

float(^oneFrom)(float);


oneFrom=^(floataFloat){

floatresult=aFloat-1.0;

returnresult;

};

Ifyoudon’texplicitlydeclarethereturnvalueofablockexpression,itcanbeautomaticallyinferredfromthecontentsoftheblock.Ifthereturntypeisinferredandtheparameterlistis 
void
,
thenyoucanomitthe 
(void)
 parameterlistaswell.Iforwhenmultiplereturnstatementsarepresent,theymustexactlymatch(usingcastingifnecessary).


GlobalBlocks

Atafilelevel,youcanuseablockasagloballiteral:

#import<stdio.h>


intGlobalInt=0;

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: