iOS笔记—block

//
//  main.m
//  block
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>


int main(int argc, const char * argv[]) {
    @autoreleasepool {

        /// 无参 无返回值
        void (^myBlock)() = ^() {
            NSLog(@"this is a block");
        };

        myBlock();


        /// 无参 有返回值
        int (^newBlock)();
        newBlock = ^int() {
            NSLog(@"this is a new block");
            return arc4random() % 100; // 返回100以内的随机数;
        };

        int domNum = newBlock();
        NSLog(@"%d",domNum);


        /// 有参 无返回值
        void (^otherBlock)(NSString * name ,int age) = ^(NSString * name ,int age){
            NSLog(@"my name is %@ , I'm %d",name,age);
        };

        otherBlock(@"张三",14);


        /// 有参 有返回值
        NSString* (^lastBlock)(NSString * name , int age) = ^(NSString * name , int age) {

            return [NSString stringWithFormat:@"my name is %@ , I'm %d",name,age];
        };

        NSString * lastInfo = lastBlock(@"李四",15);
        NSLog(@"%@", lastInfo);
    }
    return 0;
}

使用 __block 可以修改block内的局部变量

//
//  main.m
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        __block int num = 1000; 
        void (^block)(void);
        block = ^void(void){
            NSLog(@"%d", num); // 1000
            num = 9999;
        };
        block();
        NSLog(@"%d" , num); // 999
    }
    return 0;
}

一般地,定义的block名太长,通常使用typedef重定义

//
//  main.m
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

typedef NSUInteger (^myblock)(void) ;
int main(int argc, const char * argv[]) {
    @autoreleasepool {

        myblock block = ^NSUInteger(void) {
            return arc4random() % 100;
        };
        NSLog(@"%li",block());

    }
    return 0;
}

block还可以用来排序

//
//  main.m
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        NSMutableArray *arrM = [[NSMutableArray alloc] initWithArray: @[@"zhangsan",
                                                                        @"lisi",
                                                                        @"wangwu",
                                                                        @"laowang"]];
        NSLog(@"排序前 = %@", arrM);

        [arrM sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            // 以length作为比较的条件, 如果前面的长度比后面长度长,返回1;
            if ([obj1 length] > [obj2 length]) {
                return 1;
            } else
                return 0;
        }];
        NSLog(@"排序后 = %@", arrM);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csdn_hhg/article/details/80461406