iOS笔记—block

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;
}

下面简单使用block做反向传值

//  要传值的页面
//  NextViewController.h
//  block
//
//  Created by hhg on 15/9/21.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <UIKit/UIKit.h>
@interface NextViewController : UIViewController 

@property (nonatomic,strong)void(^block)(NSString* string);

@end


//
//  NextViewController.m
//  block
//
//  Created by hhg on 15/9/21.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import "NextViewController.h"

@implementation NextViewController
-(void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];

    // button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame  = CGRectMake(100, 100, 100, 100);
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)buttonClick:(UIButton *)button {
    _block(button.titleLabel.text);
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end

接收传值的页面

//
//  ViewController.m
//  block
//
//  Created by hhg on 15/9/21.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import "ViewController.h"
#import "NextViewController.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame  = CGRectMake(100, 100, 100, 100);
    [button setTitle:@"下一页" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(200, 200, 100, 100)];
    label.layer.borderWidth = 1;
    label.text = @"label";
    [label setTextAlignment:NSTextAlignmentCenter];

    [self.view addSubview:label];
}

-(void)click:(UIButton*)button {
    NextViewController *next = [[NextViewController alloc]init];

    next.block = ^(NSString* string){
        UILabel *label = (UILabel*)[self.view viewWithTag:100];
        label.text = string;
    };

    [self presentViewController:next animated:YES completion:nil];

}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值