IOS Block learning for iOS development (47)

Source: Internet
Author: User

IOS4 supports blocks directly, so it is necessary to learn about it.

In ios, blocks is an object. It encapsulates a piece of code that can be executed at any time. Blocks can be used as a function parameter or return value, and it can include an input parameter or return value. It is similar to the traditional function pointer, but there is a difference: blocks is inline and it is read-only for local variables.

Blocks definition:

Int (^ myBlock) (int a, int B) = ^ (int a, int B ){
Return a + B;
};

 

Defines a blocks object named myBlock. It has two int parameters and returns int. The right side of the equation is the specific implementation of blocks. Is it a bit like the definition of a method?

Blocks can access local variables but cannot be modified. For example, the following code will report a compilation error.

Int num = 0;
// Use block
Int (^ myBlock) (int a, int B) = ^ (int a, int B ){
Num = a + B;
Return num;
};

 

If you want to modify it, add the keyword __block (Note: there are two underlines "_")

_ Block int num = 0;
// Use block
Int (^ myBlock) (int a, int B) = ^ (int a, int B ){
Num = a + B;
Return num;
};


 

As a function parameter, blocks replaces the callback function or delegate in a sense. When the function is called, assuming an event is triggered, the content in blocks will run. This is conducive to code integration and reading, and you do not need to implement the delegate method everywhere.

Many system APIs support blocks parameters.

· Completion handlers

· Notification handlers

· Error handlers

· Enumeration

· View animation and transitions

· Sorting

For example:

[UIView animateWithDuration :( NSTimeInterval) duration animations :( void (^) () animations]

Blocks can also be used in the collection. When enumerating an array, we usually:

For (id obj in Array );

Now,

NSString * area = @ "Europe ";

NSArray * timeZoneNames = [NSTimeZone knownTimeZoneNames];

NSMutableArray * areaArray = [NSMutableArray arrayWithCapacity: 1];

NSIndexSet * areaIndexes = [timeZoneNames indexesofobjectswitexceptions: NSEnumerationConcurrent

PassingTest: ^ (id obj, NSUInteger idx, BOOL * stop ){

NSString * tmpStr = (NSString *) obj;

Return [tmpStr hasPrefix: area];

}];

NSArray * tmpArray = [timeZoneNames objectsAtIndexes: areaIndexes];

[TmpArray enumerateobjectswitexceptions: NSEnumerationConcurrent | NSEnumerationReverse

UsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop ){

[AreaArray addObject: [obj substringFromIndex: [area length] + 1];

}];

NSLog (@ "Cities in % @ time zone: % @", area, areaArray );

In blocks, obj is each member in the array. We can process each object in blocks. For example:

NSMutableArray * mArray = [NSMutableArray arrayWithObjects: @ "a", @ "B", @ "abc", nil];

NSMutableArray * mArrayCount = [NSMutableArray arrayWithCapacity: 1];

[MArray enumerateobjectswitexceptions: NSEnumerationConcurrent usingBlock: ^ (id obj, NSUInteger idx, BOOL * stop ){

[MArrayCount addObject: [NSNumber numberWithInt: [obj length];

}];

NSLog (@ "% @", mArrayCount );

You will find that writing code is easier to understand.

Finally, let's look at an example of sorting:

NSArray * stringsArray = [NSArray arrayWithObjects:

@ "String 1 ",

@ "String 21 ",

@ "String 12 ",

@ "String 11 ",

@ "String 02", nil];

Static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |

NSWidthInsensitiveSearch | NSForcedOrderingSearch;

NSLocale * currentLocale = [NSLocale currentLocale];

NSComparator finderSort = ^ (id string1, id string2 ){

Nsange string1Range = NSMakeRange (0, [string1 length]);

Return [string1 compare: string2 options: comparisonOptions range: string1Range locale: currentLocale];

};

NSLog (@ "finderSort: % @", [stringsArray sortedArrayUsingComparator: finderSort]);

Result: finderSort :(

"String 1 ",

"String 02 ",

"String 11 ",

"String 12 ",

"String 21"

)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.