IOS Dev Intro - Blocks Programming Series 01
2016-06-12 10:20
351 查看
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
Thefollowingsectionshelpyoutogetstartedwithblocksusingpracticalexamples.
Youusethe
bodyoftheblockitselfiscontainedwithin
theendofthestatement):
Theexampleisexplainedinthefollowingillustration:
Noticethattheblockisabletomakeuseofvariablesfromthesamescopeinwhichitwasdefined.
Ifyoudeclareablockasavariable,youcanthenuseitjustasyouwouldafunction:
Inmanycases,youdon’tneedtodeclareblockvariables;insteadyousimplywriteablockliteralinlinewhereit’srequiredasanargument.Thefollowingexampleusesthe
similartothestandard
Severalmethodsinthe Cocoa frameworks take
ablockasanargument,typicallyeithertoperformanoperationonacollectionofobjects,ortouseasacallbackafteranoperationhasfinished.Thefollowingexampleshowshowtouseablockwiththe
Themethodtakesasingleargument—theblock.Forillustration,inthiscasetheblockisdefinedasan
variable:
Apowerfulfeatureofblocksisthattheycanmodifyvariablesinthesamelexicalscope.Yousignalthatablockcanmodifyavariableusingthe
typemodifier.Adaptingtheexampleshownin Blocks
withCocoa,youcoulduseablockvariabletocounthowmanystringsarecomparedasequalasshowninthefollowingexample.Forillustration,inthiscasetheblockisuseddirectlyanduses
aread-onlyvariablewithintheblock:
Thisisdiscussedingreaterdetailin Blocks
andVariables.
Thefollowingsectionshelpyoutogetstartedwithblocksusingpracticalexamples.
DeclaringandUsingaBlock
Youusethe ^operatortodeclareablockvariableandtoindicatethebeginningofablockliteral.The
bodyoftheblockitselfiscontainedwithin
{},asshowninthisexample(asusualwithC,
;indicates
theendofthestatement):
intmultiplier=7; |
int(^myBlock)(int)=^(intnum){ |
returnnum*multiplier; |
}; |
Noticethattheblockisabletomakeuseofvariablesfromthesamescopeinwhichitwasdefined.
Ifyoudeclareablockasavariable,youcanthenuseitjustasyouwouldafunction:
intmultiplier=7; |
int(^myBlock)(int)=^(intnum){ |
returnnum*multiplier; |
}; |
printf("%d",myBlock(3)); |
//prints"21" |
UsingaBlockDirectly
Inmanycases,youdon’tneedtodeclareblockvariables;insteadyousimplywriteablockliteralinlinewhereit’srequiredasanargument.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); |
}); |
//myCharactersisnow{"CharlesCondomine","George","TomJohn"} |
BlockswithCocoa
Severalmethodsinthe Cocoa frameworks takeablockasanargument,typicallyeithertoperformanoperationonacollectionofobjects,ortouseasacallbackafteranoperationhasfinished.Thefollowingexampleshowshowtouseablockwiththe
NSArraymethod
.sortedArrayUsingComparator:
Themethodtakesasingleargument—theblock.Forillustration,inthiscasetheblockisdefinedasan
localNSComparator
variable:
NSArray*stringsArray=@[@"string1", |
@"String21", |
@"string12", |
@"String11", |
@"String02"]; |
staticNSStringCompareOptionscomparisonOptions=NSCaseInsensitiveSearch|NSNumericSearch| |
NSWidthInsensitiveSearch|NSForcedOrderingSearch; |
NSLocale*currentLocale=[NSLocalecurrentLocale]; |
NSComparatorfinderSortBlock=^(idstring1,idstring2){ |
NSRangestring1Range=NSMakeRange(0,[string1length]); |
return[string1compare:string2options:comparisonOptionsrange:string1Rangelocale:currentLocale]; |
}; |
NSArray*finderSortArray=[stringsArraysortedArrayUsingComparator:finderSortBlock]; |
NSLog(@"finderSortArray:%@",finderSortArray); |
/* |
Output: |
finderSortArray:( |
"string1", |
"String02", |
"String11", |
"string12", |
"String21" |
) |
*/ |
__blockVariables
Apowerfulfeatureofblocksisthattheycanmodifyvariablesinthesamelexicalscope.Yousignalthatablockcanmodifyavariableusingthe __blockstorage
typemodifier.Adaptingtheexampleshownin Blocks
withCocoa,youcoulduseablockvariabletocounthowmanystringsarecomparedasequalasshowninthefollowingexample.Forillustration,inthiscasetheblockisuseddirectlyanduses
currentLocaleas
aread-onlyvariablewithintheblock:
NSArray*stringsArray=@[@"string1", |
@"String21",//<- |
@"string12", |
@"String11", |
@"Strîng21",//<- |
@"Striñg21",//<- |
@"String02"]; |
NSLocale*currentLocale=[NSLocalecurrentLocale]; |
__blockNSUIntegerorderedSameCount=0; |
NSArray*diacriticInsensitiveSortArray=[stringsArraysortedArrayUsingComparator:^(idstring1,idstring2){ |
NSRangestring1Range=NSMakeRange(0,[string1length]); |
NSComparisonResultcomparisonResult=[string1compare:string2options:NSDiacriticInsensitiveSearchrange:string1Rangelocale:currentLocale]; |
if(comparisonResult==NSOrderedSame){ |
orderedSameCount++; |
} |
returncomparisonResult; |
}]; |
NSLog(@"diacriticInsensitiveSortArray:%@",diacriticInsensitiveSortArray); |
NSLog(@"orderedSameCount:%d",orderedSameCount); |
/* |
Output: |
diacriticInsensitiveSortArray:( |
"String02", |
"string1", |
"String11", |
"string12", |
"String21", |
"Str\U00eeng21", |
"Stri\U00f1g21" |
) |
orderedSameCount:2 |
*/ |
andVariables.
相关文章推荐
- 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-通过颜色来生成一个纯色图片
- 【代码笔记】iOS-通过颜色来生成一个纯色图片
- AVCaptureDevice 曝光模式
- IOS后台机制分析
- iOS 下的相册与图片处理