block是什么,这里就不多加强调了,它的优点:

第一:执行效率高,速度快

第二:使用起来比代理简单,省却不少代码,增强代码美感

有一些小的知识点要强调一下:

第一点:它类似于一个匿名函数,也跟java中的匿名内部类相似,但是,记住,它是一种数据类型,因为它内部是一个结构体,有方法有属性,所以它具有对象的特征;

第二点:在类中声明block为属性时,如果使用assgin修饰,那么它被放到了栈中,方法已过就会被销毁,所以,尽量使用copy作为修饰词,这样一来block就被存放到了堆中,生命周期就会延长,保证block不会被立即销毁;

第三点:要防止循环引用,造成线程死锁,所以,有时需要加上__weak修饰。

第四点:为什么多用copy修饰,而不用strong修饰,这是MRC时期遗留下来的写法习惯,其实用strong也可以修饰,但是尽量用copy。

block既可以作为属性,单独赋值然后回调;也可以作为一个方法的参数使用,再进行回调,举例如下,直接代码演示:

我的例子过程大概是:首先用户浏览题库时,点击收藏按钮,弹出收藏界面,用户选择完某一个文件夹后,隐藏收藏界面,提示收藏成功!

例子一:block使用属性单独赋值后回调

这是收藏界面类的回调代码

  1. #import <UIKit/UIKit.h>
  2.  
  3. //声明block,用作选择收藏文件后的回调处理
  4. typedef void (^CollectionBlock)(); //选择文件夹
  5. typedef void (^CompleteHandleBlock)(); //选完之后的处理
  6.  
  7. @interface KJCollectionView : UITableView
  8. @property (copy,nonatomic)CollectionBlock collectionBlock;
  9. @property (copy,nonatomic)CompleteHandleBlock completeBlock;
  10. -(instancetype)initWithFrame:(CGRect)frame withFiles:(NSArray *)files;
  11.  
  12. @end
  13.  
  14. #import "KJCollectionView.h"
  15. #import "KJMyQueBankFile.h"
  16.  
  17. @interface KJCollectionView()<UITableViewDataSource,UITableViewDelegate>
  18. @property (strong,nonatomic)NSArray *allFiles;
  19. @end
  20.  
  21. @implementation KJCollectionView
  22.  
  23. -(instancetype)initWithFrame:(CGRect)frame withFiles:(NSArray *)files
  24. {
  25. self = [super initWithFrame:frame];
  26. if (self) {
  27. self.dataSource = self;
  28. self.delegate = self;
  29. self.tableHeaderView = [UILabel createLabel:CGRectMake(, , SCREEN_WIDTH, ) title:@"请选择收藏位置" titleColor:HMColor(, , ) alignmentType:NSTextAlignmentCenter size:];
  30. self.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
  31. self.allFiles = [NSArray arrayWithArray:files];
  32. MoveUnderLine(self);
  33. }
  34. return self;
  35. }
  36.  
  37. #pragma mark - block回调,为block属性赋值
  38. -(void)setCollectionBlock:(CollectionBlock)collectionBlock{
  39. if (_collectionBlock != collectionBlock) {
  40. _collectionBlock = collectionBlock;
  41. }
  42. }
  43. -(void)setCompleteBlock:(CompleteHandleBlock)completeBlock{
  44. if (_completeBlock != completeBlock) {
  45. _completeBlock = completeBlock;
  46. }
  47. }
  48.  
  49. #pragma mark - UITableViewDataSource
  50. #pragma mark - Required
  51.  
  52. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  53. return self.allFiles.count;
  54. }
  55.  
  56. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  57.  
  58. static NSString *reuseIdentifier = @"Cell";
  59. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
  60. if (!cell) {
  61. cell = [[UITableViewCell alloc]init];
  62. }
  63. cell.accessoryView = [UIButton createButton:CGRectMake(, , , ) imageName:@"default_true" target:self Done:@selector(chooseFileDone:)];
  64. cell.imageView.image = [UIImage imageNamed:[self.allFiles[indexPath.row] file_image]];
  65. cell.textLabel.text = [self.allFiles[indexPath.row] file_Name];
  66. return cell;
  67. }
  68.  
  69. #pragma mark - Optional
  70. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  71. return ;
  72. }
  73.  
  74. #pragma mark - UITableViewDelegate
  75. #pragma mark - Optional
  76. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  77. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  78. cell.accessoryView = [UIButton createButton:CGRectMake(, , , ) imageName:@"selected_ture" target:nil Done:nil];
  79.  
  80. //回调处理
  81. _collectionBlock();
  82. _completeBlock();
  83. }
  84.  
  85. #pragma mark - 按钮选择文件夹
  86. -(void)chooseFileDone:(UIButton *)btn{
  87. UITableViewCell *cell = (UITableViewCell *)btn.superview;
  88. cell.accessoryView = [UIButton createButton:CGRectMake(, , , ) imageName:@"selected_ture" target:nil Done:nil];
  89.  
  90. //回调处理
  91. _collectionBlock();
  92. _completeBlock();
  93. }
  94. @end

这是在题库类中给block传递回调处理的代码:直接通过属性赋值

  1. #pragma mark - 点击收藏按钮时的代理方法
  2. /**
  3. * 收藏作业
  4. * @param indexPath 当前cell中选择按钮选中后的cell
  5. * @param btn 收藏按钮
  6. * @param collectionTag 当前cell中收藏按钮的tag
  7. */
  8. -(void)finishedClickedCollectionFileIndexPath:(NSIndexPath *)indexPath CollectionBtn:(UIButton *)btn{
  9.  
  10. //创建收藏文件夹视图和蒙版视图
  11. self.collectionView = [[KJCollectionView alloc]initWithFrame:CGRectMake(, , , ) withFiles:self.filesArrayM];
  12. self.collectionView.layer.cornerRadius = 3.0;
  13. self.collectionView.layer.masksToBounds = YES;
  14. self.collectionView.center = [UIApplication sharedApplication].keyWindow.center;
  15. self.coverView = [[UIView alloc]initWithFrame:self.view.bounds];
  16. self.coverView.backgroundColor = HMColorRGBA(, , , 0.3);
  17. [self.view addSubview:self.collectionView];
  18. [self.view addSubview:self.coverView];
  19. [self.view insertSubview:self.collectionView aboveSubview:self.coverView];
  20. __weak typeof(self) weakSelf = self;
  21.  
  22. //为选择文件的block赋值
  23. self.collectionView.collectionBlock = ^(){
  24. //取出收藏字典
  25. KJChooseHomeworkDicM *checkBtnDicManager = [KJChooseHomeworkDicM sharedCheckBtnDicMManager];
  26. [checkBtnDicManager.collectionDicM setObject:indexPath forKey:indexPath];
  27. [btn setSelected:YES];
  28. //获取作业模型
  29. KJLog(@"clickedCollection:%@",[weakSelf.homeworkCellFrames[indexPath.row] defaultFH]);
  30.  
  31. };
  32.  
  33. //为选完文件后的block赋值
  34. self.collectionView.completeBlock = ^(){
  35. [MBProgressHUD showSuccess:@"收藏成功"];
  36. //移除收藏文件夹视图和蒙版视图
  37. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  38. [weakSelf.collectionView removeFromSuperview];
  39. [weakSelf.coverView removeFromSuperview];
  40. [weakSelf setCollectionView:nil];
  41. [weakSelf setCoverView:nil];
  42. });
  43. };
  44. }

例子二:block作为方法的参数赋值后再进行回调

这是收藏界面类的回调代码

  1. #import <UIKit/UIKit.h>
  2.  
  3. //声明block,用作选择收藏文件后的回调处理
  4. typedef void (^CollectionBlock)(); //选择文件夹
  5. typedef void (^CompleteHandleBlock)(); //选完之后的处理
  6.  
  7. @interface KJCollectionView : UITableView
  8. @property (copy,nonatomic)CollectionBlock collectionBlock;
  9. @property (copy,nonatomic)CompleteHandleBlock completeBlock;
  10. -(instancetype)initWithFrame:(CGRect)frame withFiles:(NSArray *)files;
  11.  
  12. //声明一个方法
  13. -(void)chooseFile:(CollectionBlock )collectionBlock compeleteChooseBlock:(CompleteHandleBlock)completeBlock;
  14. @end
  15.  
  16. // Created by mac on 16/5/20.
  17. // Copyright © 2016年 mac. All rights reserved.
  18. #import "KJCollectionView.h"
  19. #import "KJMyQueBankFile.h"
  20.  
  21. @interface KJCollectionView()<UITableViewDataSource,UITableViewDelegate>
  22. @property (strong,nonatomic)NSArray *allFiles;
  23. @end
  24.  
  25. @implementation KJCollectionView
  26.  
  27. -(instancetype)initWithFrame:(CGRect)frame withFiles:(NSArray *)files
  28. {
  29. self = [super initWithFrame:frame];
  30. if (self) {
  31. self.dataSource = self;
  32. self.delegate = self;
  33. self.tableHeaderView = [UILabel createLabel:CGRectMake(, , SCREEN_WIDTH, ) title:@"请选择收藏位置" titleColor:HMColor(, , ) alignmentType:NSTextAlignmentCenter size:];
  34. self.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
  35. self.allFiles = [NSArray arrayWithArray:files];
  36. MoveUnderLine(self);
  37. }
  38. return self;
  39. }
  40.  
  41. #pragma mark - block回调,通过方法为block属性赋值
  42. -(void)chooseFile:(CollectionBlock )collectionBlock compeleteChooseBlock:(CompleteHandleBlock)completeBlock{
  43.  
  44. if (_collectionBlock != collectionBlock) {
  45. _collectionBlock = collectionBlock;
  46. }
  47. if (_completeBlock != completeBlock) {
  48. _completeBlock = completeBlock;
  49. }
  50. }
  51.  
  52. #pragma mark - UITableViewDataSource
  53. #pragma mark - Required
  54.  
  55. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  56. return self.allFiles.count;
  57. }
  58.  
  59. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  60.  
  61. static NSString *reuseIdentifier = @"Cell";
  62. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
  63. if (!cell) {
  64. cell = [[UITableViewCell alloc]init];
  65. }
  66. cell.accessoryView = [UIButton createButton:CGRectMake(, , , ) imageName:@"default_true" target:self Done:@selector(chooseFileDone:)];
  67. cell.imageView.image = [UIImage imageNamed:[self.allFiles[indexPath.row] file_image]];
  68. cell.textLabel.text = [self.allFiles[indexPath.row] file_Name];
  69. return cell;
  70. }
  71.  
  72. #pragma mark - Optional
  73. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  74. return ;
  75. }
  76.  
  77. #pragma mark - UITableViewDelegate
  78. #pragma mark - Optional
  79. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  80. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  81. cell.accessoryView = [UIButton createButton:CGRectMake(, , , ) imageName:@"selected_ture" target:nil Done:nil];
  82.  
  83. //回调处理
  84. _collectionBlock();
  85. _completeBlock();
  86. }
  87.  
  88. #pragma mark - 按钮选择文件夹
  89. -(void)chooseFileDone:(UIButton *)btn{
  90. UITableViewCell *cell = (UITableViewCell *)btn.superview;
  91. cell.accessoryView = [UIButton createButton:CGRectMake(, , , ) imageName:@"selected_ture" target:nil Done:nil];
  92.  
  93. //回调处理
  94. _collectionBlock();
  95. _completeBlock();
  96. }
  97. @end

这是在题库类中给block传递回调处理的代码:直接将要赋值的block写入到方法中

  1. #pragma mark - 点击收藏按钮时的代理方法
  2. /**
  3. * 收藏作业
  4. * @param indexPath 当前cell中选择按钮选中后的cell
  5. * @param btn 收藏按钮
  6. * @param collectionTag 当前cell中收藏按钮的tag
  7. */
  8. -(void)finishedClickedCollectionFileIndexPath:(NSIndexPath *)indexPath CollectionBtn:(UIButton *)btn{
  9.  
  10. //创建收藏文件夹视图和蒙版视图
  11. self.collectionView = [[KJCollectionView alloc]initWithFrame:CGRectMake(, , , ) withFiles:self.filesArrayM];
  12. self.collectionView.layer.cornerRadius = 3.0;
  13. self.collectionView.layer.masksToBounds = YES;
  14. self.collectionView.center = [UIApplication sharedApplication].keyWindow.center;
  15. self.coverView = [[UIView alloc]initWithFrame:self.view.bounds];
  16. self.coverView.backgroundColor = HMColorRGBA(, , , 0.3);
  17. [self.view addSubview:self.collectionView];
  18. [self.view addSubview:self.coverView];
  19. [self.view insertSubview:self.collectionView aboveSubview:self.coverView];
  20. __weak typeof(self) weakSelf = self;
  21.  
  22. //把block放入方法中
  23. [self.collectionView chooseFile:^{
  24. //取出收藏字典
  25. KJChooseHomeworkDicM *checkBtnDicManager = [KJChooseHomeworkDicM sharedCheckBtnDicMManager];
  26. [checkBtnDicManager.collectionDicM setObject:indexPath forKey:indexPath];
  27. [btn setSelected:YES];
  28. [MBProgressHUD showSuccess:@"收藏成功"];
  29.  
  30. //获取作业模型
  31. KJLog(@"clickedCollection:%@",[weakSelf.homeworkCellFrames[indexPath.row] defaultFH]);
  32.  
  33. } compeleteChooseBlock:^{
  34.  
  35. //移除收藏文件夹视图和蒙版视图
  36. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  37. [MBProgressHUD hideHUD];
  38. [weakSelf.collectionView removeFromSuperview];
  39. [weakSelf.coverView removeFromSuperview];
  40. [weakSelf setCollectionView:nil];
  41. [weakSelf setCoverView:nil];
  42. });
  43. }];
  44. }

上面两种演示截图达到的效果是一样的:

点击题库中的收藏                     选择文件夹收藏      

    

显示收藏成功                      移除文件夹视图

    

本人原创,转载须注明出处,谢谢!

iOS:使用block代码块实现事件处理过程中的回调的更多相关文章

  1. iOS - OC Block 代码块

    前言 Block 是一段预先准备好的代码,可以在需要的时候执行,可以当作参数传递.Block 可以作为函数参数或者函数的返回值,而其本身又可以带输入参数或返回值.Block 是 C 语言的,类似于一个 ...

  2. block(代码块)的介绍以及使用方法和变量之间的关系

    http://blog.csdn.net/menxu_work/article/details/8762848 block(代码块)的介绍以及使用方法和变量之间的关系 block(代码块)的介绍以及使 ...

  3. ios开发 block语句块

    ios开发 block语句块 1.block 理解为匿名函数 2.block变量的定义 //定义block变量,^表示定义block //技巧:函数名左右加括号,在函数名前面在加^ void (^bl ...

  4. IOS开发之----代码块的使用(二)

    iOS4引入了一个新特性,支持代码块的使用,这将从根本上改变你的编程方式.代码块是对C语言的一个扩展,因此在Objective-C中完全支持.如果你学过Ruby,Python或Lisp编程语言,那么你 ...

  5. block代码块介绍

    关于block的简单介绍 什么是block? Block是C语言的一个语法特性,同时也是C语言的运行时特性,它很像C中的函数指针,因为你可以像使用函数指针一样的去使用block对象:它也很像C++中的 ...

  6. Block代码块中使用局部变量注意点

    第一次写代码遇到报这个错,实在是想不通为什么,按常理应该是不会有问题,报错的呀??纠结了一会之后只好仔细查看报错原因咯,原来是: 当我们在block代码块中使用局部变量时,就会很容易出现如图的错误. ...

  7. eclipse实现代码块折叠-类似于VS中的#region……#endregion

    背 景 刚才在写代码的时候,写了十几行可以说是重复的代码: 如果整个方法或类中代码多了,感觉它们太TM占地方了,给读者在阅读代码上造成很大的困难,于是想到能不能把他们“浓缩”成一行,脑子里第一个闪现出 ...

  8. 【玩转Eclipse】——eclipse实现代码块折叠-类似于VS中的#region……#endregion

    [玩转Eclipse]——eclipse实现代码块折叠-类似于VS中的#region……#endregion http://www.cnblogs.com/Micheal-G/articles/507 ...

  9. IOS学习4——block代码块

    本文转载自:iOS开发-由浅至深学习block 一.关于block 在iOS 4.0之后,block横空出世,它本身封装了一段代码并将这段代码当做变量,通过block()的方式进行回调.这不免让我们想 ...

随机推荐

  1. Mybatis学习 PageHelper分页插件

    1.Maven依赖,注意使用PageHelper时的版本必须与Mybatis版本对应 1 <!-- 添加Mybatis依赖 --> 2 <dependency> 3 <g ...

  2. LeetCode解题报告—— Search in Rotated Sorted Array & Search for a Range & Valid Sudoku

    1. Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated(轮流,循环) at so ...

  3. LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum

    1. 1-bit and 2-bit Characters We have two special characters. The first character can be represented ...

  4. WordPress 前端投稿/编辑发表文章插件 DJD Site Post(支持游客和已注册用户)汉化版 免费下载

    插件简介 前面逍遥乐给大家推荐了 WordPress用户前端化专业版WP User Frontend Pro WordPress中文汉化插件v2.1.9 今天逍遥乐给大家带来的wordpress插件是 ...

  5. AC日记——Sagheer, the Hausmeister codeforces 812b

    812B - Sagheer, the Hausmeister 思路: 搜索: 代码: #include <cstdio> #include <cstring> #includ ...

  6. 文本检查点web_reg_find和web_find两个函数的区别

    LR脚本实战:文本检查点web_reg_find和web_find两个函数的区别   web_reg_find是先注册(register)后查找的:使用时将它放在请求语句的前面. 而web_find是 ...

  7. 四十九 常用内建模块 urllib

    urllib提供了一系列用于操作URL的功能. Get urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应: 例如,对豆瓣的一个 ...

  8. Java数组的十大方法

    Java数组的十大方法 以下是Java Array的前10种方法.他们是来自stackoverflow的投票最多的问题. 0.声明一个数组 String[] aArray = new String[5 ...

  9. Codeforces 1099 D. Sum in the tree-构造最小点权和有根树 贪心+DFS(Codeforces Round #530 (Div. 2))

    D. Sum in the tree time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  10. 转:西部数据NAS设备hack

    通过该文学习一下常见硬件web漏洞.重点关注一下几个方面: 1.登录验证代码: 2.文件上传代码: 3.system/exec/popen等是否存在注入可能: 4.调用二进制文件: 5.未登陆可以访问 ...