OC Block, Array advanced

Source: Internet
Author: User

Main content:

?, block syntax

?, block make?

Third, block to achieve array sorting

About Block

Blocks: Block syntax, which is essentially an anonymous function (a function without a name)

The standard C-face does not have a block,c version of the language, plus the anonymous function.

C + +, JS, swift and other language, there is a similar syntax, called closures. The block syntax is similar to a function pointer.

Review function pointers

function pointer (variable): A pointer variable that holds the address of a function (the name of a functor).

Int (*p) (int x,int y) = sum;

function pointer type: INT (*) (int x,int y) is a pointer to two integer parameters, an integer that returns a value function.

function pointer variable: p

Value of function pointer: sum

Block

anonymous function: A function without a name.

such as int (int x, int y)

Because block is an anonymous function, the implementation of the function that the block variable holds can be directly adjusted by the block variable. function

How does a function with no name be tuned? (If you have a name, you can adjust it directly, or you can use the function pointer to adjust it)

// 1. ^: de-    char // in oc language, ' ^ ' denotes block block         // declares a block variable    int (^sumblock) (intint) = ^ (intint  b) {        return A +B;    };    NSLog (@ "%d", Sumblock (ten));

 int  (^maxblock) (int , int ) = ^ ( Span style= "color: #0000ff;" >int  A,  b) { 3  return  a > B?  a:b;  4  };  5  int  a = Maxblock (10 , 20  );  6  NSLog (@ " %d  , a);  

Block return value type: Int (^maxblock) (int a, int b)

Block variable: A, b

The value stored by the block variable: is the implementation part

That is: ^ return value type (parameter list) function body

Block for typedef

typedef in (^BLOCKTYPE) (int x, int y)

Primitive type: Int (^) (int x, int y)

New Type: Blocktype

// an alias    for the block type int (^maxblock) (intint);     =^ (intint  b) {        return a + B;    };    NSLog (@ "%d", SumBlock1 (ten));

The relationship between block and local distribution variables

//the relationship between Block and local variables//int abc = 897; //Local Variables//__block modified to modify local variables__blockintCount = -; void(^sayhi) (int) = ^(intc) {         for(inti =0; I < count; i++) {NSLog (@"Hey"); }//ABC = 90; //Local variables can be used, local variables cannot be modified           }; Sayhi ( -);

The relationship between block and local distribution variables

//Global VariablesintCount = $;intMainintargcConst Char*argv[]) {    //Block and global variables    void(^addnum) (void) = ^(void) {Count++; NSLog (@"count =%d", Count);    }; //calledAddnum (); //Show ResultsNSLog (@"count =%d", count);

// Exercise 1 Using block to convert a string to a shaping function    int (^strint) (NSString *) = ^ (NSString *string) {        return [string  intvalue];    };     int num = strint (@ "890");    NSLog (@ "%d", num);

Block array sorting

  block array sorting  Nsarray *stringarray = [nsarray arraywithobjects:@ " a18  , @"    , @"   +  , @"            nil]; Nscomparator Sortblock  = ^ (id  string1, id   string2) { return   [string1 compare:string2]; }; 

//Pass the block as a parameter to the method

    *sortarray = [Stringarray sortedarrayusingcomparator:sortblock];    NSLog (@ "sortarray:%@", Sortarray);

//Use block to sort the dynamic array//non-variable group usage two need to be received in the front2    Nsmutablearray *agearray = [Nsmutablearray arraywithobjects:@"113",@" the",@" About", nil];3     //fa Yi4Nscomparisonresult (^sortblock) (ID,ID) = ^(IDObj1,IDobj2) {5         if([Obj1 Intvalue] >[Obj2 Intvalue]) {6            returnnsordereddescending;7}Else if([Obj1 Intvalue] <[Obj2 Intvalue]) {8            returnnsorderedascending;9}Else{Ten             returnNsorderedsame; One         } A     }; -     //passing a block as a parameter to a method - [Agearray Sortusingcomparator:sortblock]; theNSLog (@"%@", Agearray); -     //Law II (using this method) -[Agearray Sortusingcomparator:^nscomparisonresult (IDOBJ3,IDobj4) { -        if([Obj3 intvalue] >[Obj4 Intvalue]) { +            returnnsorderedascending; -}Else{ +            returnNsorderedsame; A        } at}];

1. Create a person class
Instance variable: _name _age
Method: Initialize Method
Convenience Builder
Assignment and value method of instance variable
2. Create 3 person objects and put them in the array
3. In person, add the Comparebyname: method, use this method to sort the array, and output
4. Use block to sort by the age of person and output

//Sort by agePerson *person1 = [Person Personwith:@"da"Age +]; person*person2 = [Person Personwith:@"ji"Age -]; person*person3 = [Person Personwith:@"Ko"Age2]; Nsmutablearray*array =[Nsmutablearray Arraywithobjects:person1,person2,person3, Nil]; [Array Sortusingcomparator:^nscomparisonresult (IDObj1,IDobj2) {        if([Obj1 Getage] >[Obj2 Getage]) {            returnnsordereddescending; }Else {            returnNsorderedsame;    }    }]; NSLog (@"%@", array);

Literal quantity

OC Block, Array advanced

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.