IOS Dev Intro - Blocks Programming Series 05
2016-06-12 10:22
267 查看
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Blocks/Articles/bxUsing.html#//apple_ref/doc/uid/TP40007502-CH5-SW1
Ifyoudeclareablockasavariable,youcanuseitasyouwouldafunction,asshowninthesetwoexamples:
Frequently,however,youpassablockastheargumenttoafunctionoramethod.Inthesecases,youusuallycreateablock“inline”.
Youcanpassablockasafunctionargumentjustasyouwouldanyotherargument.Inmanycases,however,youdon’tneedtodeclareblocks;insteadyousimplyimplementtheminlinewherethey’rerequiredasan
argument.Thefollowingexampleusesthe
similartothestandard
Noticethattheblockiscontainedwithinthefunction’sargumentlist.
Thenextexampleshowshowtouseablockwiththe
declaredasfollows:
Thefunctionsubmitsablocktoadispatchqueueformultipleinvocations.Ittakesthreearguments;thefirstspecifiesthenumberofiterationstoperform;thesecondspecifiesaqueuetowhichtheblockis
submitted;andthethirdistheblockitself,whichinturntakesasingleargument—thecurrentindexoftheiteration.
Youcanuse
Cocoa provides
anumberofmethodsthatuseblocks.Youpassablockasamethodargumentjustasyouwouldanyotherargument.
Thefollowingexampledeterminestheindexesofanyofthefirstfiveelementsinanarraythatappearinagivenfilterset.
Thefollowingexampledetermineswhetheran
setsthevalueofanotherlocalvariable(
stopsthesearch)ifitdoes.Noticethat
andthattheblockisdefinedinline:
Typically,youshouldn’tneedtocopy(orretain)ablock.Youonlyneedtomakeacopywhenyouexpecttheblocktobeusedafterdestructionofthescopewithinwhichitwasdeclared.Copyingmovesablock
totheheap.
YoucancopyandreleaseblocksusingCfunctions:
Toavoidamemoryleak,youmustalwaysbalancea
Ablockliteral(thatis,
theblock. Thescopeofthestack-localdatastructureisthereforetheenclosingcompoundstatement,soyoushould avoid thepatternsshowninthefollowingexamples:
Youcansetbreakpointsandsinglestepintoblocks.YoucaninvokeablockfromwithinaGDBsessionusing
asillustratedinthisexample:
IfyouwanttopassinaCstring,youmustquoteit.Forexample,topass
youwouldwritethefollowing:
UsingBlocks
InvokingaBlock
Ifyoudeclareablockasavariable,youcanuseitasyouwouldafunction,asshowninthesetwoexamples:int(^oneFrom)(int)=^(intanInt){ |
returnanInt-1; |
}; |
printf("1from10is%d",oneFrom(10)); |
//Prints"1from10is9" |
float(^distanceTraveled)(float,float,float)= |
^(floatstartingSpeed,floatacceleration,floattime){ |
floatdistance=(startingSpeed*time)+(0.5*acceleration*time*time); |
returndistance; |
}; |
floathowFar=distanceTraveled(0.0,9.8,1.0); |
//howFar=4.9 |
UsingaBlockasaFunctionArgument
Youcanpassablockasafunctionargumentjustasyouwouldanyotherargument.Inmanycases,however,youdon’tneedtodeclareblocks;insteadyousimplyimplementtheminlinewherethey’rerequiredasanargument.Thefollowingexampleusesthe
qsort_bfunction.
qsort_bis
similartothestandard
qsort_rfunction,buttakesablockasitsfinalargument.
char*myCharacters[3]={"TomJohn","George","CharlesCondomine"}; |
qsort_b(myCharacters,3,sizeof(char*),^(constvoid*l,constvoid*r){ |
char*left=*(char**)l; |
char*right=*(char**)r; |
returnstrncmp(left,right,1); |
}); |
//Blockimplementationendsat"}" |
//myCharactersisnow{"CharlesCondomine","George","TomJohn"} |
Thenextexampleshowshowtouseablockwiththe
dispatch_applyfunction.
dispatch_applyis
declaredasfollows:
voiddispatch_apply(size_titerations,dispatch_queue_tqueue,void(^block)(size_t)); |
submitted;andthethirdistheblockitself,whichinturntakesasingleargument—thecurrentindexoftheiteration.
Youcanuse
dispatch_applytriviallyjusttoprintouttheiterationindex,asshown:
#include<dispatch/dispatch.h> |
size_tcount=10; |
dispatch_queue_tqueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); |
dispatch_apply(count,queue,^(size_ti){ |
printf("%u\n",i); |
}); |
UsingaBlockasaMethodArgument
Cocoa providesanumberofmethodsthatuseblocks.Youpassablockasamethodargumentjustasyouwouldanyotherargument.
Thefollowingexampledeterminestheindexesofanyofthefirstfiveelementsinanarraythatappearinagivenfilterset.
NSArray*array=@[@"A",@"B",@"C",@"A",@"B",@"Z",@"G",@"are",@"Q"]; |
NSSet*filterSet=[NSSetsetWithObjects:@"A",@"Z",@"Q",nil]; |
BOOL(^test)(idobj,NSUIntegeridx,BOOL*stop); |
test=^(idobj,NSUIntegeridx,BOOL*stop){ |
if(idx<5){ |
if([filterSetcontainsObject:obj]){ |
returnYES; |
} |
} |
returnNO; |
}; |
NSIndexSet*indexes=[arrayindexesOfObjectsPassingTest:test]; |
NSLog(@"indexes:%@",indexes); |
/* |
Output: |
indexes:<NSIndexSet:0x10236f0>[numberofindexes:2(in2ranges),indexes:(03)] |
*/ |
NSSetobjectcontainsawordspecifiedbyalocalvariableand
setsthevalueofanotherlocalvariable(
found)to
(andYES
stopsthesearch)ifitdoes.Noticethat
foundisalsodeclaredasa
__blockvariable,
andthattheblockisdefinedinline:
__blockBOOLfound=NO; |
NSSet*aSet=[NSSetsetWithObjects:@"Alpha",@"Beta",@"Gamma",@"X",nil]; |
NSString*string=@"gamma"; |
[aSetenumerateObjectsUsingBlock:^(idobj,BOOL*stop){ |
if([objlocalizedCaseInsensitiveCompare:string]==NSOrderedSame){ |
*stop=YES; |
found=YES; |
} |
}]; |
//Atthispoint,found==YES |
CopyingBlocks
Typically,youshouldn’tneedtocopy(orretain)ablock.Youonlyneedtomakeacopywhenyouexpecttheblocktobeusedafterdestructionofthescopewithinwhichitwasdeclared.Copyingmovesablocktotheheap.
YoucancopyandreleaseblocksusingCfunctions:
Block_copy(); |
Block_release(); |
Block_copy()with
Block_release().
PatternstoAvoid
Ablockliteral(thatis, ^{...})istheaddressofa stack-local datastructurethatrepresents
theblock. Thescopeofthestack-localdatastructureisthereforetheenclosingcompoundstatement,soyoushould avoid thepatternsshowninthefollowingexamples:
voiddontDoThis(){ |
void(^blockArray[3])(void); //anarrayof3blockreferences |
for(inti=0;i<3;++i){ |
blockArray[i]=^{printf("hello,%d\n",i);}; |
//WRONG:Theblockliteralscopeisthe"for"loop. |
} |
} |
voiddontDoThisEither(){ |
void(^block)(void); |
inti=random(): |
if(i>1000){ |
block=^{printf("gotiat:%d\n",i);}; |
//WRONG:Theblockliteralscopeisthe"then"clause. |
} |
//... |
} |
Debugging
Youcansetbreakpointsandsinglestepintoblocks.YoucaninvokeablockfromwithinaGDBsessionusing invoke-block,
asillustratedinthisexample:
$invoke-blockmyBlock1020 |
thisstringintothe
doSomethingWithStringblock,
youwouldwritethefollowing:
$invoke-blockdoSomethingWithString"\"thisstring\"" |
相关文章推荐
- IOS Dev Intro - Blocks Programming Series 04
- IOS Dev Intro - Blocks Programming Series 03
- IOS Dev Intro - Blocks Programming Series 02
- IOS Dev Intro - Blocks Programming Series 01
- iOS调用perform selector超过2个参数以上的方法
- iOS开发:编辑框格式化输入、删除、插入
- IOS之NSArray 中调用的方法详解
- iOS - 富文本AttributedString
- iOS平台下cookie的使用
- iOS ipv6 兼容
- iOS 笔记
- iOS小莲花Versions的SVN工具不能提交.a文件的解决方法
- iOS开发 引入支付宝需要注意的地方
- iOS9新特性(二)
- IPv6介绍及程序支持IPv6的障碍
- 关于 iOS socket 都在这里了
- iOS教你轻松打造瀑布流Layout
- iOS 独立开发记录(下)
- iOS 独立开发记录(上)
- 【代码笔记】iOS-通过颜色来生成一个纯色图片