Primary Use of ios block

Source: Internet
Author: User

Primary Use of ios block

Block and GCD are required for the interview of ios senior programmers. This article first introduces block

Part 1: Overview


Block is a C-level syntax and a feature of runtime. It is similar to a function (function pointer) in Standard C, but its operation requires support from the compiler and runtime, block has been well supported since ios4.0. I personally feel that the greatest convenience of block usage is the simplified callback process. Previously, when using uiview animations, the process must control the animation and process it accordingly, after ios4.0, uiview adds block support. Now, you only need to use a simple block code to directly add the animation after the animation is completed in the Code part of the animation, in addition, when using notification, the block is also very helpful. If you use it more, the block greatly improves the code efficiency,

Block is an embedded function with anonymous functions. It is very similar to a function. However, the flexibility of Block is reflected in the reference of stack memory and heap memory, we can even pass a Block as a parameter to other functions or blocks.

The entity format is as follows:

^ (Input parameter column) {behavior subject}

The lock object starts with "^", followed by the parameter columns wrapped in parentheses (such as int a, int B, int c), and the behavior subject is wrapped in braces, the private name is block literal. The behavior subject can return the value with return, and the type will be automatically identified by compiler. If no parameter Column exists, it must be written as ^ (void ).

Part 2: Usage


I. Primary usage of block

/* Test 1 uses the ^ operator to declare a block Variable */int multiplier = 7; int (^ myblock) (int) = ^ (int num) {return num * multiplier;}; printf ("% d \ n", myblock (5 )); /* test 2 writes the block content directly in an embedded manner where block is needed */char * myCharacters [3] = {"TomJohn", "George ", "Charles Condomine"}; qsort_ B (myCharacters, 3, sizeof (char *), ^ (const void * l, const void * r) // sorting function, I personally think sort is very easy to use. {char * left = * (char **) l; char * right = * (char **) r; return strncmp (left, right, 1) ;}); printf ("% s \ n", myCharacters [0]);/* test 3 modify the variable */_ block int multiplier2 = 7 in the block; int (^ myblock2) (int) = ^ (int num) {if (num> 5) {multiplier2 = 0 ;}else {multiplier2 = 3 ;}return multiplier2 ;}; NSLog (@ "% d, % d \ n", myblock2 (8), myblock2 (3 ));

Ii. Define a block

For details, refer to the Entity form of block.

/* Return void. The parameter is also the void block */void (^ blockReturningVoidWithVoidArgument) (void);/* return an integer, the two parameters are integer and metaform blocks */int (^ blockReturningIntWithIntAndCharArguments) (int, char);/* return void, array containing 10 blocks, each block has an integer parameter */void (^ arrayofTenBlockReturningVoidWinIntArgument [10]) (int );

3. block and variable

/* How to use the test 1 Regional variable * // Add the _ block modifier variable to modify int x = 123 in the block; void (^ printXAndY) (int) = ^ (int y) {printf ("% d, % d \ n", x, y) ;}; printXAndY (20 ); // Add the _ block modifier variable to operate on the block/* interaction between variables of test 2 and the block */NSInteger localCounter = 42; _ block char localCharacter; void (^ aBlock) (void) = ^ (void) {// + CounterGlobal; // It can be accessed + + CounterStatic; // It can be accessed // CounterGlobal = localCounter; localCharacter = 'a';}; ++ localCounter; localCharacter = 'B'; aBlock (); printf ("test2: % ld, % ld, % c \ n ", localCounter, CounterStatic, localCharacter );
4. Use block

/* Test 1 when a block is declared as a variable, we can use it like a common function */int (^ twoFrom) (int) = ^ (int anInt) {return anInt-1;}; printf ("1 from 10 is % d \ n", twoFrom (10); float (^ distanceTraveled) (float, float, float) = ^ (float startingSpeed, float acceleration, float time) {float distance = (startingSpeed * time) + (0.5 * acceleration * time); return distance ;}; printf ("howFar % f \ n", distanceTraveled (0.0, 9.8, 1.0);/* test 2 If block is used as a parameter to pass in the function, we usually use an embedded method to use block */char * myCharacter_s [3] = {"TomJohn", "George", "Charles Condomine"}; qsort_ B (myCharacter_s, 3, sizeof (char *), ^ (const void * l, const void * r) {char * left = * (char **) l; char * right = * (char **) r; return strncmp (left, right, 1) ;});/* test 3 in the above example, block itself is part of the function parameter. In the next example, use block in the dispatch -- apply function. The definition of dispatch_apply is as follows * // void dispatch_apply (size_t iterations, dispatch_queue_t queue, void (^ block) (size_t); size_t count = 12; dispatch_queue_t queue = dispatch_get_global_queue (queue, 0); dispatch_apply (count, queue, ^ (size_t I) {// similar to for loop printf ("% zu \ n", I * 2) ;});/* test 4 SDK provides many block-based methods, we can pass a block like passing a common parameter, the following example shows how to retrieve the index value of the data we want from the first five pieces of data in an array * // all the data NSArray * array = [NSArray arrayWithObjects: @ "A", @ "B", @ "C", @ "A", @ "B", @ "Z", @ "G", @ "are ", @ "Q", nil]; // We only need the NSSet * filterSet = [NSSet setWithObjects: @ "A", @ "B", @ "Z ", @ "Q", nil]; BOOL (^ test) (id obj, NSUInteger idx, BOOL * stop); test = ^ (id obj, NSUInteger idx, BOOL * stop) {if (idx <5) {if ([filterSet containsObject: obj]) {return YES ;}return NO ;}; NSIndexSet * indexes = [array indexesOfObjectsPassingTest: test]; NSLog (@ "indexes: % @", indexes );

If the similarities are purely coincidences

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.