How to Use block in IOS -- How to Use blocks with IOS

Source: Internet
Author: User
Tags ranges

 

Block helps us organize independent code segments and improve reusability and readability. Ios4 introduces this feature in uikit. Blocks are used for more than 100 Apple APIs, so this is a must-start knowledge.

What is block? 
You can use^To declare a block variable, which indicates the beginning of a block.

 
 
  1. int num1 = 7;  
  2. int(^aBlock)(int) = ^)int num2) {  
  3.    return num1+nunm2;  
  4. };  

In the above Code, we declare a block as a variable, so we can use it as a function:

 
 
  1. NSLog(@"%d", aBlock(49)); //adds 49 to 7 which gives us 56.  

We have just looked at block as a variable, but we usually use block in an internal connection mode, for example, in a variable. The API either uses a block to perform an operation on an object set or uses it as the callback after an operation is completed.

 
 
  1. NSComperator compareStringsBlock = ^(id stringA, id stringB) {  
  2. NSRange rangeS  = NSMakeRange (0, [stringA length]);  
  3.   return (stringA compare:stringB options:comparisonOptions range:rangeS locale:currentLocale];  
  4. };  
  5.  
  6. NSArray *compareSortArray  = [arrayOfStringDays sortArrayUsingComparator: compareStringsBlock]);  

Block has the advantage of creating a temporary function as an expression. The Apple document states:
Block is an anonymous Inline code set that meets the following requirements:

  • A parameter list of the specified type is the same as a function.
  • There is a type of return value that can be deduced or declared
  • It can capture the State from its defined meaning range.
  • You can change the state of the word meaning range as needed.
  • It can share the possibility of changes with other blocks defined in the same word scope.
  • You can continue to share and modify the state of the Meaning range (stack frame) after the meaning range (stack frame) is destroyed.

A block is a self-contained small code segment that encapsulates the task units used for Traversing (linear traversal) or callback and can be executed concurrently.

Declare and use block 
The Apple document describes how to declare a block as a variable and use it as a function:

 
 
  1. INT (^ onefrom) (INT) = ^ (INT anint ){
  2. Return anint-1;
  3. };
  4. // We have created an inline block ^ (INT anint)... and its function body and result are passed to another block named onefrom.
  5.  
  6. Printf ("1 from 10 is % d", onefrom (10 ));
  7. // Print out: "1 from 10 is 9"
  8. // This block function (distancetraveled) passes in three float parameters and returns the float value.
  9.  
  10. Float (^ distancetraveled) (float, float, float) =
  11.  
  12. ^ (Float startingspeed, float acceleration, float time ){
  13. Float distance = (startingspeed * Time) + (0.5 * acceleration * time );
  14. Return distance;
  15. };

You can also pass in a block as a parameter, instead of declaring them in the above way, so that you can easily implement the block as a parameter by associating the code in the same way.

 
 
  1. NSArray *anArray = [NSArray arrayWithObjects: @"cat", @"dog",nil];  
  2. sortFunction(anArray, ^(string *a string *b){  
  3. if ( a == @"cat") return TRUE; }); 

In this way, we can see that an inline block code segment occupies the position of the last parameter (which must be the last parameter in the parameter list. Cocoa provides a lot of block-based methods, so that you can pass in the block as a method parameter:

 
 
  1. NSArray *array = [NSArray arrayWithObjects: @"A", @"B", @"C",  nil];  
  2. NSSet *filterSet = [NSSet setWithObjects: @"A", @"Z", @"Q", nil];  
  3.  
  4. BOOL (^test)(id obj, NSUInteger idx, BOOL *stop); //Block declaration returns BOOL, params inc. id and BOOL  
  5. //body of block gets the block literal ^(id obj, NSUInteger idx, Bool *stop)... and the body logic   
  6. test = ^ (id obj, NSUInteger idx, BOOL *stop) {  
  7.     if (idx < 5) {  
  8.         if ([filterSet containsObject: obj]) {  
  9.             return YES;  
  10.         }  
  11.     }  
  12.     return NO;  
  13.  
  14. }; 

Another example provided by Apple is:

 
 
  1. __block BOOL found = NO;  
  2. NSSet *aSet = [NSSet setWithObjects: @"Alpha", @"Beta", @"Gamma", @"X", nil];  
  3. NSString *string = @"gamma";  
  4. //we provide below a way of how to enumerate, using our own compare logic  
  5. [aSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {  
  6.     if ([obj localizedCaseInsensitiveCompare:string] == NSOrderedSame) {  
  7.         *stop = YES;  
  8.         found = YES;  
  9.     }  
  10. }]; 

As you can see, it takes a little while to have it sink in but once you get it, it's quite simple. I suggest looking at Apple's documentation, as well as looking at the referenced APIs to see how they are used. practice makes perfect.

 

Source: http://answers.oreilly.com/topic/2281-how-to-use-blocks-with-ios/

 

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.