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

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.


DeclaringandUsingaBlock

Youusethe 
^
 operatortodeclareablockvariableandtoindicatethebeginningofablockliteral.The
bodyoftheblockitselfiscontainedwithin 
{}
,asshowninthisexample(asusualwithC, 
;
 indicates
theendofthestatement):

intmultiplier=7;

int(^myBlock)(int)=^(intnum){

returnnum*multiplier;

};

Theexampleisexplainedinthefollowingillustration:


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_b
 function. 
qsort_b
 is
similartothestandard 
qsort_r
 function,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 take
ablockasanargument,typicallyeithertoperformanoperationonacollectionofobjects,ortouseasacallbackafteranoperationhasfinished.Thefollowingexampleshowshowtouseablockwiththe
NSArray
 method 
sortedArrayUsingComparator:
.
Themethodtakesasingleargument—theblock.Forillustration,inthiscasetheblockisdefinedasan 
NSComparator
 local
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 
__block
 storage
typemodifier.Adaptingtheexampleshownin Blocks
withCocoa,youcoulduseablockvariabletocounthowmanystringsarecomparedasequalasshowninthefollowingexample.Forillustration,inthiscasetheblockisuseddirectlyanduses 
currentLocale
 as
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

*/

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