Objective-c----Block, array sort

Source: Internet
Author: User
Tags array sort


Directly on the code:
// Write? A return value is an integer parameter is NSString (only one parameter
// number) block to implement the function of converting a string to an integer.

// int (NSString * string) {
// return [string intValue];
//}

// Assign ^ int (NSString * string) to int (^ myBlock) (NSString *)
// ^ int (NSString * string) is an anonymous function whose parameter is NSString * type and whose return value is int type
// can be defined outside the main () function
// The data type of the block represents the format of the anonymous function (return value type, formal parameter type)
// The definition of the block variable is similar to the definition of the function pointer variable, the only difference from the function pointer variable is that the variable name is modified by the caret ‘^’ before the variable name.
// First of all, it should be decorated with ^. The remaining part is consistent with the C language function definition. The biggest difference is that there is no function name (the return value type can also be omitted).
// When a block variable is defined, it has the basic characteristics of variable definition. The anonymous function to the right of the assignment number can be assigned as a whole, similar to int a = 5;
// The value assigned by the block variable is an anonymous function, which also has the characteristics of the function, and is the only one that can be defined inside a function implementation (in C, functions are not nested and defined, and block is a special case)
    int (^ myBlock) (NSString *) = ^ int (NSString * string) {
        return [string intValue];
    };
    NSLog (@ "% d", myBlock (@ "123") + 1);

// int (^ sumBlock) (int, int) = ^ (int number1, int number2) This is also OK
    int (^ sumBlock) (int, int) = ^ int (int number1, int number2) {
        return number1 + number2;
    };
    NSLog (@ "% d", sumBlock (sumBlock (1, 2), sumBlock (3, 4)));

// The type definition of the analog function pointer, the format is the same as the function pointer, the type definition simplifies the use of the block to some extent
// typedef int (^ BlockType) (int, int);
    BlockType sum = ^ int (int n, int m) {
        return m + n;
    };
    NSLog (@ "% d", sum (2, 3));

// __block indicates that the variables defined by it can be used in the block function body;
// The __block type identifier can allow local variables to be accessed normally inside the block that it subsequently defines
// (Note: set __block int count = 0; cannot be defined behind the __block function body)
    __block int count = 8;

    void (^ testBlock) () = ^ () {
// int count = 9;
// __block int count = 6; // XXXX cuo wu
        for (int i = 0; i <10; i ++) {
            count ++;
            NSLog (@ "% d", count);
        }
    };
// __block int count = 8;
// NSLog (@ "% d", count);
    // block call
    testBlock ();

    NSComparisonResult (^ comareResult) (NSString *, NSString *) = ^ (NSString * str1, NSString * str2) {
        return [str1 compare: str2];
    };
    NSLog (@ "% ld", comareResult (@ "456", @ "123"));


    / *
     * Array Sort
     * /

    NSArray * array = @ [@ 1, @ 3, @ 2, @ 5, @ 4];
    NSArray * resultArray1 = [array sortedArrayUsingSelector: @selector (compare :)];
    NSLog (@ "% @", resultArray1);

    __block int number = 0;
    NSComparator sortBlock = ^ (id obj1, id obj2) {
        number ++;
        return [obj2 compare: obj1];
    };
    NSLog (@ "% d", number); // execute first

    NSArray * resultArray2 = [array sortedArrayUsingComparator: sortBlock];
    NSLog (@ "% d", number);
    NSLog (@ "% @", resultArray2);

    // can also be written like this

    // NSArray * resultArray3 = [array sortedArrayUsingComparator: ^ (id obj1, id obj2)
    NSArray * resultArray3 = [array sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2) {
        return [obj2 compare: obj1];
    }];
    NSLog (@ "% @", resultArray3);



    / *
     * Exercise two,
     *
     * For the above example array
     * 1. Sorted in ascending order by student number
     * 2, in descending order of student number
     * 3. Sort by name in ascending order
     * 4. Sort by name in descending order
     * /

    Student * stu1 = [Student studentWithName: @ "wang" number: 1001 age: 23];
    Student * stu2 = [Student studentWithName: @ "zhen" number: 1003 age: 22];
    Student * stu3 = [Student studentWithName: @ "gang" number: 1002 age: 24];

    NSArray * strArray = [[NSArray alloc] initWithObjects: stu1, stu2, stu3, nil];

    NSLog (@ "% @", [strArray sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2) {
        return [[obj1 getName] compare: [obj2 getName]];
    }]);

    NSLog (@ "% @", [strArray sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2) {
        return [[NSString stringWithFormat: @ "% d", [obj1 getNumber]] compare: [NSString stringWithFormat: @ "% d", [obj2 getNumber]]];
    }]);

    NSLog (@ "% @", [strArray sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2) {
        return [[NSString stringWithFormat: @ "% d", [obj1 getAge]] compare: [NSString stringWithFormat: @ "% d", [obj2 getAge]]];
    }]);


    NSMutableArray * stus = [NSMutableArray array];
    NSArray * names = @ [@ "Duke", @ "Douglas", @ "Allen", @ "Lily", @ "Lucy", @ "Jack", @ "Rose", @ "Jeams", @ "Tom" , @ "Frank"];
    for (int i = 0; i <10; i ++) {
        Student * stu = [Student studentWithName: names [i] number: arc4random ()% 9000 + 1000 age: arc4random ()% 100];
        [stus addObject: stu];
    }
    NSLog (@ "% @", stus);


    // Note: Difference: [strArray sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2)
    [stus sortUsingComparator: ^ NSComparisonResult (id obj1, id obj2) {

// return [[obj1 getName] compare: [obj2 getName]];

        NSInteger age1 = [obj1 getAge];
        NSInteger age2 = [obj2 getAge];
        if (age1 <age2) {
            return NSOrderedDescending;
        }
        else if (age1> age2) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    NSLog (@ "% @", stus); 


Student.h file:


//
// Student.h
//
// Created by on 15/4/7.
// Copyright (c) 2015. All rights reserved.
//

#import <Foundation / Foundation.h>

@interface Student: NSObject
{
     NSString * _name; // name
     int _number; // student number
     int _age; // age

     @protected
     NSString * _a;
     @private
     NSString * _b;

}

-(instancetype) initWithName: (NSString *) name
                       number: (int) number
                          age: (int) age;
+ (instancetype) studentWithName: (NSString *) name
                          number: (int) number
                             age: (int) age;

-(NSString *) getName;
-(int) getNumber;
-(int) getAge;


@end // Student 


STUDENT.M file:


 
// //  Student.m // //  Created by  on 15/4/7. //  Copyright (c) 2015年 . All rights reserved. // #import "Student.h" @implementation Student - (instancetype)initWithName:(NSString *)name
                      number:(int)number
                         age:(int)age { if ( self = [super init] ) {
        _name = name ;
        _number = number ;
        _age = age ;
    } return self ;
}

+ (instancetype)studentWithName:(NSString *)name
                         number:(int)number
                            age:(int)age { return [[Student alloc] initWithName:name number:number age:age] ;
}

- (NSString *)getName { return _name ;
}

- (int)getNumber { return _number ;
}

- (int)getAge { return _age ;
}

- (NSString *)description { return [[NSString alloc] initWithFormat:@"%@ %d %d", _name , _number , _age ] ;
} @end // Student


Objective-c----Block, array sort


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.