学会使用Block编程

1.Block是什么?

Block是一个C级别的语法以及运行时的一个特性,和标准C中的函数(函数指针)类似,可以看成一个语句块或者更多时候看成一个匿名函数。

+ (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations NS_AVAILABLE_IOS(4_0);
[ UIView animateWithDuration:10 animations:^{
       NSLog(@"%@,",@"block");
    }]; 

2.Block在什么情况下使用?

Block除了能够定义参数列表、返回类型外,还能够获取被定义时的词法范围内的状态(比如局部变量),并且在一定条件下(比如使用__block变量)能够修改这些状态。此外,这些可修改的状态在相同词法范围内的多个block之间是共享的,即便出了该词法范围(比如栈展开,出了作用域),仍可以继续共享或者修改这些状态。通常来说,block都是一些简短代码片段的封装,适用作工作单元,通常用来做并发任务、遍历、以及回调。

3.Block如何申明?(对比于c语言中的函数申明)

4.如何调用Block?(类比于函数指针)

 int (*CFunc) (int a) //函数调用
 int result = CFunc(10);
 int (^BFunc) (int  a)  //Block调用
 int result = BFunc(10);

5.Block编程实例(实现回调)

#import <UIKit/UIKit.h>
/**
 *  点击按钮的回调
 *
 *  @param selectIndex selectIndex 点击的索引值
 */
typedef void(^DialogViewCompleteHandle)(NSUInteger selectIndex);

@interface ViewController : UIViewController

@property (nonatomic,copy) DialogViewCompleteHandle completeHandle;

- (void)showDialogViewWithHandle:(void (^)(NSUInteger selectIndex))handler;
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#import "ViewController.h"

@interface ViewController ()
{
    UIView *_view;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)showAlert:(id)sender {

    [self showDialogViewWithHandle:^(NSUInteger selectIndex) {
        if (selectIndex == 0) {
            NSLog(@"第一个按钮被点击了!");
        }else
        {
            NSLog(@"第二个按钮被点击了!");
        }
    }];

}

- (void)showDialogViewWithHandle:(void (^)(NSUInteger selectIndex)) handler
{
    _view = [UIView new];
    _view.center = CGPointMake(SCREEN_WIDTH /2, SCREEN_HEIGHT / 2);
    _view.bounds = CGRectMake(0, 0, SCREEN_WIDTH /2, SCREEN_HEIGHT /2);
    _view.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_view];
    CGRect viewFrame = _view.frame;

    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.center = CGPointMake(viewFrame.size.width /2, viewFrame.size.height /2 - 50);
    button1.bounds = CGRectMake(0, 0, 60, 40);
    button1.tag = 0;
    [button1 setTitle:@"button1" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [_view addSubview:button1];

    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.center = CGPointMake(viewFrame.size.width /2, viewFrame.size.height /2 + 50);
    button2.bounds = CGRectMake(0, 0, 60, 40);
    button2.tag = 1;
    [button2 addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [button2 setTitle:@"button2" forState:UIControlStateNormal];
    [_view addSubview:button2];

    _view.transform = CGAffineTransformMakeScale(0.01, 0.01);

    [UIView animateWithDuration:0.3 animations:^{
        _view.transform = CGAffineTransformMakeScale(1.0, 1.0);

    }];

    self.completeHandle = handler;
}

- (void)clickButton:(UIButton *)sender
{
    NSUInteger selIndex = sender.tag;

    if (_completeHandle) {
        _completeHandle(selIndex);
    }

    [self closeView];
}
- (void)closeView{
    [UIView animateWithDuration:0.3 animations:^{
        _view.transform = CGAffineTransformMakeScale(0.01, 0.01);
        [_view removeFromSuperview];
    }];
}
@end

点击button1 和 button2 可以实现按钮的回调Block

Demo下载地址

时间: 2024-10-22 05:01:25

学会使用Block编程的相关文章

(译)IOS block编程指南 1 介绍

Introduction(介绍) Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block ca

IOS多线程之Block编程

1 什么是block iOS SDK 4.0開始,Apple引入了block这一特性.字面上说,block就是一个代码块.可是它的奇妙之处在于在内联(inline)运行的时候(这和C++非常像)还能够传递參数. 同一时候block本身也能够被作为參数在方法和函数间传递.这就给予了block无限的可能. 对于闭包(block),有非常多定义.当中闭包就是可以读取其他函数内部变量的函数,这个定义即接近本质又较好理解. 对于刚接触Block的同学,会认为有些绕,由于我们习惯写这种程序main(){ f

(译)IOS block编程指南 2 block开始

Getting Started with Blocks(开始block) The following sections help you to get started with blocks using practical examples. 接下来这一节有实用的例子帮你开始blocks. Declaring and Using a Block (定义和使用block) You use the ^ operator to declare a block variable and to indic

(译文)IOS block编程指南 4 声明和创建blocks

Declaring and Creating Blocks (声明和创建blocks) Declaring a Block Reference (声明一个block引用) Block variables hold references to blocks. You declare them using syntax similar to that you use to declare a pointer to a function, except that you use ^ instead o

(译文)IOS block编程指南 3 概念总览

Conceptual Overview(概览) Block objects provide a way for you to create an ad hoc function body as an expression in C, and C-derived languages such as Objective-C and C++. In other languages and environments, a block object is sometimes also called a “

IOS block编程指南 1 介绍

Introduction(介绍) Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block ca

IOS block编程指南 2 block开始

Getting Started with Blocks(开始block) The following sections help you to get started with blocks using practical examples. 接下来这一节有实用的例子帮你开始blocks. Declaring and Using a Block (定义和使用block) You use the ^ operator to declare a block variable and to indic

搞懂了这几点,你就学会了Web编程

整理参考自<刘欣 程序猿> 1.理解浏览器/服务器结构 (B/S)B/S 是从 90年代的客户端/服务器端发展而来, 共同点都是由一个(或一组)服务器来服务多个客户端. 差别在于:首先,C/S结构的客户端可能是由不同语言编写的,例如VB,Delphi, PowerBuilder等, B/S结构中浏览器成为了一个通用的客户端, 程序以Web的方式呈现,不需要安装,服务器端的升级就意味着所有客户端的升级,这和C/S相比是个翻天覆地的变化.其次B/S的访问协议也标准化为HTTP(s)  ,而不是原来

学会这些 pycharm 编程小技巧,编程效率提升 10 倍

PyCharm 是一款非常强大的编写 python 代码的工具.掌握一些小技巧能成倍的提升写代码的效率,本篇介绍几个经常使用的小技巧. 一.分屏展示 当你想同时看到多个文件的时候: 1.右击标签页: 2.选择 move right 或者 split vertical: 3.效果. 二.远程 Python 解释器 1.解释器设置里点击设置: 2.选择 docker, ssh 等远程解释器. 三.Live Templates live templates 主要是偷懒用的,采用事先定义好的模板,一个按