Start with block 2 in IOS block programming guide

Source: Internet
Author: User

Start with block 2 in IOS block programming guide
Getting Started with Blocks (start block)

The following sections help you to get started with blocks using practical examples.

Next, we will take a practical example to help you start blocks. Declaring and Using a Block (define and use block)

You use^Operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained{}, As shown in this example (as usual with C,;Indicates the end of the statement ):

You use the ^ operation to define a block value and indicate the beginning of a block. The topic of the block is surrounded by {}, as shown in the example (like a semicolon in C; declares the end of a statement ):

 

int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};

The example is explained in the following procedure:

This example is explained in the following illustration:

The return value of myBlock is int type. We use ^ to declare a myBlock block. Only one parameter is required, which is of the int type. The parameter name is num. This is a block definition. assign values to myblock. This is the subject of the block.

Notice that the block is able to make use of variables from the same scope in which it was defined.

If you declare a block as a variable, you can then use it just as you wowould a function:

Note: block can be used to define variables used for block definition.

If you define a block as a variable, you can use a block like a function.

int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};
 
printf(%d, myBlock(3));
// prints 21
Using a Block Directly (Use block Directly)

In your cases, you don't need to declare block variables; instead you simply write a block literal inline where it's required as an argument. The following example usesqsort_bFunction.qsort_bIs similar to the standardqsort_rFunction, but takes a block as its final argument.

In many cases, you do not need to define a block as a variable. On the contrary, you can directly write a block as a parameter. In the following example, the qsort_ B function is used. qsort_ B is similar to the standard qsort_r function and uses a block as the last parameter.

char *myCharacters[3] = { TomJohn, George, Charles Condomine };
 
qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r) {
    char *left = *(char **)l;
    char *right = *(char **)r;
    return strncmp(left, right, 1);
});
 
// myCharacters is now { Charles Condomine, George, TomJohn }
Blocks with Cocoa (block in cocoa)

Several methods in the Cocoa frameworks take a block as an argument, typically either to perform an operation on a collection of objects, or to use as a callback after an operation has finished. the following example shows how to use a block withNSArrayMethodsortedArrayUsingComparator:. The method takes a single argument-the block. For authentication, in this case the block is defined asNSComparatorLocal variable:

There are some methods in the Cocoa framework that use block as a parameter, especially for operations on multiple objects, or callback after an operation is completed. The following example shows how NSArray uses block in method sortedArrayUsingComparator. This method uses the block parameter. To illustrate, this block is defined as a local variable of the NSComparator type:

NSArray *stringsArray = @[ @string 1,
                           @String 21,
                           @string 12,
                           @String 11,
                           @String 02 ];
 
static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
 
NSComparator finderSortBlock = ^(id string1, id string2) {
 
    NSRange string1Range = NSMakeRange(0, [string1 length]);
    return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
};
 
NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@finderSortArray: %@, finderSortArray);
 
/*
Output:
finderSortArray: (
    string 1,
    String 02,
    String 11,
    string 12,
    String 21
)
*/
_ Block Variables (_ block type variable)

A powerful feature of blocks is that they can modify variables in the same lexical scope. You signal that a block can modify a variable using__blockStorage type modifier. adapting the example shown in Blocks with Cocoa, you can use a block variable to count how many strings are compared as equal as shown in the following example. for authentication, in this case the block is used directly and usescurrentLocaleAs a read-only variable within the block:

Another powerful feature of block is the ability to modify variables in the same lexical range. You can declare the variable to be modified in a block to be of the _ block type. In the example of rewriting Blocks with Cocoa, you can use the block variable in the following example to calculate how many strings are the same. To illustrate the need, block is used directly in the example, and currentLocate is used as the read-only variable in the block.

NSArray *stringsArray = @[ @string 1,
                          @String 21, // <-
                          @string 12,
                          @String 11,
                          @Strîng 21, // <-
                          @Striñg 21, // <-
                          @String 02 ];
 
NSLocale *currentLocale = [NSLocale currentLocale];
__block NSUInteger orderedSameCount = 0;
 
NSArray *diacriticInsensitiveSortArray = [stringsArray sortedArrayUsingComparator:^(id string1, id string2) {
 
    NSRange string1Range = NSMakeRange(0, [string1 length]);
    NSComparisonResult comparisonResult = [string1 compare:string2 options:NSDiacriticInsensitiveSearch range:string1Range locale:currentLocale];
 
    if (comparisonResult == NSOrderedSame) {
        orderedSameCount++;
    }
    return comparisonResult;
}];
 
NSLog(@diacriticInsensitiveSortArray: %@, diacriticInsensitiveSortArray);
NSLog(@orderedSameCount: %d, orderedSameCount);
 
/*
Output:
 
diacriticInsensitiveSortArray: (
    String 02,
    string 1,
    String 11,
    string 12,
    String 21,
    StrU00eeng 21,
    StriU00f1g 21
)
orderedSameCount: 2
*/

This is discussed in greater detail in Blocks and Variables.

For more details, see Blocks and Variables.

 



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.