Blocks Programming Topics

Source: Internet
Author: User

Getting Started with Blocksdeclaring and Using a Block

use The ^ operator to declare a block variable and indicate the start of the block. Body in {} The following example:

int multiplier = 7;

Int (^myblock) (int) = ^ (int num) {

return num * multiplier;
};
};

Examples are explained below:

You can see that the block body can access {} and you are the same scope variable.

If you declare a block as a variable, you can use it like a function, for example:

  int multiplier = 7;
  Int (^myblock) (int) = ^ (int num) {
      return num * multiplier;
  };
  printf ("%d", Myblock (3));
Prints "21"

Using a Block Directly

In many cases you do not need to declare a block variable, but simply write block inline as a parameter. The following example uses the Qsort_b function. Qsort_b is similar to the standard Qsort_r function, but the block is used as a 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

The following example shows how to use the Block and Nsarray methods Sortedarrayusingcomparator: This method has a block parameter. To illustrate, the block is defined as the Nscomparator local variable.

Nsarray *stringsarray = @[@ "String 1",                             @ "string",                             @ "string",                             @ "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",      "string One",      "string",      "string 21"

) */

__block Variables

The __block type indicates that the variable can be changed in the block body.

  Nsarray *stringsarray = @[@ "String 1",
@ "string",//<-@ "string", @ "string one", @ "Str?ng",//<-@ "stri?g",//<-@ "string 02"];
Nslocale *currentlocale = [Nslocale currentlocale];__block nsuinteger orderedsamecount = 0;
Nsarray *diacriticinsensitivesortarray = [stringsarraysortedarrayusingcomparator:^ (ID string1, id string2) {
    Nsrange string1range = nsmakerange (0, [string1 length]);
    Nscomparisonresult Comparisonresult = [string1 Compare:string2options: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 One", "string", "string 21",

"Str\u00eeng 21",
      "STRI\U00F1G"  )
  Orderedsamecount:2  * *
Conceptual overviewBlock functionality
    • Block is an anonymous code for the inline collection
    • There is a type parameter similar to function
    • Has a return type
    • Can capture the state within its defined range
    • Can have a choice to change the state within the defined range
    • You can continue to share and change the definition state after the definition scope is destroyed
Usage

Blocks represents a small-scale, self-capacitance code fragment. They are particularly important as encapsulation units when performing concurrent tasks. The advantages of block different from the traditional callback function are:

1, they allow you to write code where one of the calls after the method executes

2, they allow access to local variables

Declaring and Creating Blocksdeclaring a Block Reference

voID (^blockreturningvoidwithvoidargument) (void);

Int (^blockreturningintwithintandchararguments) (int, char);

void (^arrayoftenblocksreturningvoidwithintargument[10]) (int);

Blocks that do not have a return type must be shown as void type

You can also create block types when you use specific signature in multiple places

typedef float (^myblocktype) (float, float);
Myblocktype Myfirstblock =//...; Myblocktype Mysecondblock =//...;
Creating a Block

The following example defines a simple block and assigns it to a previously declared variable, Onefrom.

Float (^onefrom) (float);
Onefrom = ^ (float afloat) {    float result = aFloat-1.0;    return result;

};

Global Blocks
#import <stdio.h>
int globalint = 0;int (^getglobalint) (void) = ^{return globalint;};
Blocks and Variables

Variables of type 5

    • Global variables, including static locals
    • Global functions
    • Local variables and Parameters form an enclosing scope
    • __block Varibales
    • Const IMPROTS
Object and Block Variablesobjective-c Objects

When you copy a block, it creates a strong reference to the object variable. If you say use block in one of the execution methods:

If you access an instance variable by reference, a strong reference to self is generated

If you access an instance variable by value, a strong reference to the variable is generated

Dispatch_async (queue, ^{      //instancevariable are used by reference, a strong reference are made to self      dosomethingw Ithobject (instancevariable);

});

  ID localvariable = instancevariable;  Dispatch_async (Queue, ^{
              /* localvariable is used by value, a strong reference are made to localvariable (and not to self        ).

*/

      Dosomethingwithobject (localvariable);  });
Using Blocksinvoking a Block

If you declare a block as a variable, you can use it in a function, for example:

Int (^onefrom) (int) = ^ (int anint) {    return anInt-1;

};

printf ("1 from-is%d", onefrom);//Prints "1 from 9"
Float (^distancetraveled) (float, float, float) =                         ^ (float startingspeed, float acceleration, float time) {
    float distance = (Startingspeed * time) + (0.5 * acceleration * time * time);
    return distance;};
float Howfar = distancetraveled (0.0, 9.8, 1.0);//Howfar = 4.9
Using a Block as a Function Argument

You can

Blocks Programming Topics

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.