Object-C-code Block
The code block in OC is an extension of the C language introduced by iOS4.0 + and Mac OS X 10.6 + to implement the features of anonymous functions. Similar to the closures or Lambda expressions in other language scripting or programming languages, it may seem weird at first glance, but the Block will get bigger and bigger during development, it is better to know more. There are also a lot of Block content. This article describes the basic concepts and practices of Block from the perspective of actual use. First, let's look at an example on the Apple Website: int (^ Multiply) (int, int) = ^ (int num1, int num2) {return num1 * num2 ;}; int result = Multiply (7, 4); // Result is 28. the code above defines a Block, similar to the delegate in C #. int indicates the return type, ^ indicates the key identifier, and (int, int) indicates the parameter type. Note that, the normal method is to wrap the return type with (). Here we wrap the Block name. There is a similar picture on the Internet. You can refer to it: in addition to defining the parameter list and return type, Block can also obtain the status within the defined lexical range (after passing variables as parameters, you can modify them and return them ). blocks are the encapsulation of some short code snippets and are suitable for work units. They are usually used for concurrent tasks, traversal, and callback. The following is an example of a notification:-(void) viewDidLoad {[super viewDidLoad]; [[nsicationicationcenter defaultCenter] addObserver: self selector: @ selector (keyboardWillShow :) name: UIKeyboardWillShowNotification object: nil];}-(void) keyboardWillShow :( NSNotification *) notification {// Notification-handling code goes here .} the above is an example of calling the addServer method, but it can also be written as follows:-(void) viewDidLoad {[super viewDidLoad]; [[nsicationicationcenter default Center] addObserverForName: UIKeyboardWillShowNotification object: nil queue: [NSOperationQueue mainQueue] usingBlock: ^ (NSNotification * notif) {// Notification-handling code goes here.}];} the Block usage example on the official website of Apple may not be so easy to understand for the first time. If you carefully read the definition of addServerName, you will find:-(id <NSObject>) addObserverForName :( NSString *) name object :( id) obj queue :( NSOperationQueue *) queue usingBlock :( void (^) (NSNotification * note) block NS_AV AILABLE (10_6, 4_0); the Block parameter is defined as follows: (void (^) (NSNotification * note) block NS_AVAILABLE (10_6, 4_0) the content enclosed in parentheses. The first is the return value type, and the subsequent content is enclosed in brackets ^. The latter is the transfer type. Based on the above understanding, you can write it as void (^ MyBlock) (NSNotification *) = ^ (NSNotification * note) {note = nil;}; [[nsicationicationcenter defacenter center] addObserverForName: jsonobject: nil queue: [NSOperationQueue mainQueue] usingBlock: MyBlock]; block in Apple's API documentation You can see it everywhere. In common cases, when a task is completed, the callback processing of the message listener, the error callback processing, the enumeration callback, the view animation, the transformation, and the sorting are as follows: -(void) enumeratekeysandobjectswitexceptions :( NSEnumerationOptions) opts usingBlock :( void (^) (id key, id obj, BOOL * stop) block NS_AVAILABLE (10_6, 4_0 ); call when the task is completed:-(IBAction) animateView :( id) sender {CGRect cacheFrame = self. imageView. frame; [UIView animateWithDuration: 1.5 animations: ^ {CGRect newFrame = self. imageView. fram E; newFrame. origin. y = newFrame. origin. y + 150.0; self. imageView. frame = newFrame; self. imageView. alpha = 0.2;} completion: ^ (BOOL finished) {if (finished) {// Revert image view to original. self. imageView. frame = cacheFrame; self. imageView. alpha = 1.0 ;}}];} processing in the notification mechanism:-(void) applicationDidFinishLaunching :( NSNotification *) aNotification {opQ = [[NSOperationQueue alloc] init]; [NSNotificatio NCenter defaultCenter] addObserverForName: @ "CustomOperationCompleted" object: nil queue: opQ usingBlock: ^ (NSNotification * notif) {NSNumber * theNum = [notif. userInfo objectForKey: @ "NumberOfItemsProcessed"]; NSLog (@ "Number of items processed: % I", [theNum intValue]);}];} calls when enumerating Arrays: NSString * area = @ "Europe"; NSArray * timeZoneNames = [NSTimeZone knownTimeZoneNames]; NSMutableArray * areaArray = [NSMut AbleArray objects: 1]; NSIndexSet * areaIndexes = [timeZoneNames values: 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 Block: ^ (id obj, NSUInteger idx, BOOL * stop) {[areaArray addObject: [obj substringFromIndex: [area length] + 1];}]; NSLog (@ "Cities in % @ time zone: % @", area, areaArray); you can also write a Block to intercept a string and do something you need: NSString * musician = @ "Beatles"; NSString * musicDates = [NSString stringWithContentsOfFile: @ "/usr/share/calendar. music "encoding: NSASCIIStringEncoding error: NULL]; [musicDates enumerateSubstringsI NRange: NSMakeRange (0, [musicDates length]-1) options: NSStringEnumerationByLines usingBlock: ^ (NSString * substring, nsange substringRange, nsange enclosingRange, BOOL * stop) {nsange found = [substring rangeOfString: musician]; if (found. location! = NSNotFound) {NSLog (@ "% @", substring) ;}}]; view animation and conversion practices: [UIView animateWithDuration: 0.2 animations: ^ {view. alpha = 0.0;} completion: ^ (BOOL finished) {[view removeFromSuperview];}]; animation between two views: [UIView transitionWithView: containerView duration: 0.2 options: Invalid animations: ^ {[fromView removeFromSuperview]; [containerView addSubview: toView]} completion: NULL]; array sorting practice: NSArray * stringsArray = [NSArray arrayWithObjects: @ "string 1 ", @ "String 21", @ "string 12", @ "String 11", @ "String 02", nil]; static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | queries | 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]);