1、block的特点:
     block是C语言;
     block是一种数据类型、可以当做参数,也可以用做返回值;——总之,对比int的用法用即可(当然,定义的时候,最好跟函数对比);
     block是预先准备好的代码块、在需要的时候调用,(需要好好理解“需要时”);
 
2、定义block
     有返回值、有参数:返回类型 ^(blockName)(参数) =  ^返回类型(参数列表){///代码 };
     无返回值、有参数:void ^(blockName)(参数) = ^(参数列表){///代码 };
     无返回值、无参数: void (^blockName)() = ^ { /// 代码实现; }; 
     上面这么多,也记不住:
     速记代码快:inlineBlock ,编译器会提示:(根据需要删减就好了);
 

3、block引用外部变量
      在定义block时,如果使用了外部变量,block内部会默认对外部变量做一次copy;
      默认情况下,不允许在block内部修改外部变量的值;
      在外部变量声明时,使用__block修饰符,则可以在block内部修改外部变量的值;
 
4、 数组的遍历&排序;
      遍历:enumerateObjectsUsingBlock:
                所有的参数都已经准备到位,可以直接使用
                效率比for高,官方推荐使用;
               举例:懒加载
               enumerateObjectsUsingBlock遍历:
               [tempArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL*_Nonnull stop) {
           NSDictionary *dict = (NSDictionary*)obj;
            Heros *hero = [HerosherosWithDict:dict];
            [ArrMaddObject:hero]; 
        }];
        for—IN遍历: 
       for (NSDictionary*dict in tempArray) {
            Heros *heros = [HerosherosWithDict:dict];
            [ArrM addObject:heros];
        }
 
      排序:sortedArrayUsingComparator:
5、block的数据的逆向传值
    
     被调用方:
               准备块代码;
               
     调用方:
                定义块代码属性,在适当的时候调用block;
     
     举例:(以下三个举例实现了自定义NSOperation,异步下载一张图片,并在主线程中显示)
          调用方:
                       定义块代码属性
  1. #import <Foundation/Foundation.h>
  2. #import <UIKit/UIKit.h>
  3. @class YSCNSOperationOP;
  4. typedef void(^setUpUIImage)(YSCNSOperationOP *);
  5. @interface YSCNSOperationOP : NSOperation
  6. @property (nonatomic, copy) NSString *urlString;
  7. @property (nonatomic, strong) UIImage *image;
  8. @property (nonatomic, copy) setUpUIImage myBlock;
  9. - (void)setUpUIImage:(setUpUIImage )block;
  10. @end

在适当的时候执行:   

  1. #import "YSCNSOperationOP.h"
  2. @implementation YSCNSOperationOP
  3. - (void)main {
  4. @autoreleasepool {
  5. UIImage *image  = [self downLoadImage:self.urlString];
  6. self.image = image;
  7. dispatch_async(dispatch_get_main_queue(), ^{
  8. self.myBlock(self);
  9. });
  10. }
  11. }
  12. - (UIImage *)downLoadImage:(NSString *)urlString{
  13. NSURL *url = [NSURL URLWithString:urlString];
  14. NSData *data = [NSData dataWithContentsOfURL:url];
  15. UIImage *image = [UIImage imageWithData:data];
  16. return image;
  17. }
  18. - (void)setUpUIImage:(setUpUIImage )block {
  19. if (block) {
  20. self.myBlock = block;
  21. }
  22. }
  23. @end
     被调用方:
                         准备代码块:
 
  1. #import "ViewController.h"
  2. #import "YSCNSOperationOP.h"
  3. @interface ViewController ()
  4. @property (weak, nonatomic) IBOutlet UIImageView *iamgeView;
  5. @end
  6. @implementation ViewController
  7. - (void)viewDidLoad {
  8. [super viewDidLoad];
  9. // Do any additional setup after loading the view, typically from a nib.
  10. }
  11. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  12. YSCNSOperationOP *yscOp = [[YSCNSOperationOP alloc] init];
  13. yscOp.urlString = @"http://h.hiphotos.baidu.com/image/pic/item/9825bc315c6034a8094ace24c9134954082376ee.jpg";
  14. [yscOp setUpUIImage:^(YSCNSOperationOP *op) {
  15. self.iamgeView.image = op.image ;
  16. }];
  17. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  18. [queue addOperation:yscOp];
  19. }
  20. @end
其它方式的逆向传值:
 
           一、代理:
                    代理方:
                                1)遵守协议;
                                2)设置代理;
                                3)实现代理方法;
                    
                    委托方:
                                1)定义协议;
                                2)代理属性;
                                3)在需要的时候通知代理;‘
   
举例
                     委托方:定义协议;
                                      代理属性;
 
  1. #import <Foundation/Foundation.h>
  2. #import <UIKit/UIKit.h>
  3. @class YSCNSOperation;
  4. @protocol YSCNSOperationDelegate <NSObject>
  5. - (void)yscNSOperation:(YSCNSOperation *)operation withImage:(UIImage *)image;
  6. @end
  7. @interface YSCNSOperation : NSOperation
  8. @property (nonatomic, copy) NSString *urlString;
  9. @property (nonatomic, strong) UIImage *image;
  10. @property (nonatomic, weak) id<YSCNSOperationDelegate> delegate;
  11. @end

在需要的时候通知代理:

  1. #import "YSCNSOperation.h"
  2. @implementation YSCNSOperation
  3. - (void)main {
  4. @autoreleasepool {
  5. UIImage *image  = [self downLoadImage:self.urlString];
  6. self.image = image;
  7. dispatch_async(dispatch_get_main_queue(), ^{
  8. if ([self.delegate respondsToSelector:@selector(yscNSOperation:withImage:)]) {
  9. [self.delegate yscNSOperation:self withImage:image];
  10. }
  11. });
  12. }
  13. }
  14. - (UIImage *)downLoadImage:(NSString *)urlString{
  15. NSURL *url = [NSURL URLWithString:urlString];
  16. NSData *data = [NSData dataWithContentsOfURL:url];
  17. UIImage *image = [UIImage imageWithData:data];
  18. return image;
  19. }
  20. @end

代理方:

  1. #import "ViewController.h"
  2. #import "YSCNSOperation.h"
  3. @interface ViewController () <YSCNSOperationDelegate>
  4. @property (weak, nonatomic) IBOutlet UIImageView *iamgeView;
  5. @end
  6. @implementation ViewController
  7. - (void)viewDidLoad {
  8. [super viewDidLoad];
  9. }
  10. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  11. static dispatch_once_t onceToken;
  12. dispatch_once(&onceToken, ^{
  13. YSCNSOperation *yscOp = [[YSCNSOperation alloc] init];
  14. yscOp.delegate = self;
  15. yscOp.urlString = @"http://h.hiphotos.baidu.com/image/pic/item/9825bc315c6034a8094ace24c9134954082376ee.jpg";
  16. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  17. [queue addOperation:yscOp];
  18. });
  19. }
  20. - (void)yscNSOperation:(YSCNSOperation *)operation withImage:(UIImage *)image {
  21. self.iamgeView.image = operation.image;
  22. }
  23. @end
        二、通知:
                    通知方:注册通知;
                    观察者:注册观察者;
                                   移除观察者对象;
               
                     举例:
                    通知方注册通知、并在恰当的时候发出通知:
  1. #import "YSCNSOperation.h"
  2. @implementation YSCNSOperation
  3. - (void)main {
  4. @autoreleasepool {
  5. UIImage *image  = [self downLoadImage:self.urlString];
  6. self.image = image;
  7. dispatch_async(dispatch_get_main_queue(), ^{
  8. [[NSNotificationCenter defaultCenter] postNotificationName:@"setUpUI" object:self];
  9. });
  10. }
  11. }
  12. - (UIImage *)downLoadImage:(NSString *)urlString{
  13. NSURL *url = [NSURL URLWithString:urlString];
  14. NSData *data = [NSData dataWithContentsOfURL:url];
  15. UIImage *image = [UIImage imageWithData:data];
  16. return image;
  17. }
  18. @end
 
           观察者:注册观察者、移除观察者
  1. #import "ViewController.h"
  2. #import "YSCNSOperation.h"
  3. @interface ViewController ()
  4. @property (weak, nonatomic) IBOutlet UIImageView *iamgeView;
  5. @end
  6. @implementation ViewController
  7. - (void)viewDidLoad {
  8. [super viewDidLoad];
  9. // Do any additional setup after loading the view, typically from a nib.
  10. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lookNotifi:) name:@"setUpUI" object: nil nil];
  11. }
  12. - (void)lookNotifi:(NSNotification *)notifi{
  13. YSCNSOperation *op= (YSCNSOperation *)notifi.object;
  14. self.iamgeView.image = op.image;
  15. //self.iamgeView.image =  (UIImage *)notifi.object;
  16. }
  17. - (void)dealloc {
  18. [[NSNotificationCenter defaultCenter] removeObserver:self];
  19. }
  20. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  21. YSCNSOperation *yscOp = [[YSCNSOperation alloc] init];
  22. yscOp.urlString = @"http://h.hiphotos.baidu.com/image/pic/item/9825bc315c6034a8094ace24c9134954082376ee.jpg";
  23. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  24. [queue addOperation:yscOp];
  25. }
  26. @end

iOS-Block总结 && 全面解析逆向传值的更多相关文章

  1. iOS 代理与block 逆向传值 学习

    一般在项目中出现逆向传值的时候就需要用到代理.block 或者通知中心了.由于公司的项目底层封装的很好,所以项目做了三四个月就算碰到需要逆传的情况也不用自己处理.但是最近遇到了一个特别的情况就需要自己 ...

  2. iOS Block界面反向传值

    在上篇博客 <iOS Block简介> 中,侧重解析了 iOS Block的概念等,本文将侧重于它们在开发中的应用. Block是iOS4.0+ 和Mac OS X 10.6+ 引进的对C ...

  3. NSNotification,NSNotificationCenter的使用、iOS中五种对象间传值的方式

    学习内容 NSNitification与NotificationCenter(通知与通知中心) 通知的使用 [[NSNotificationCenter defaultCenter]addObserv ...

  4. iOS block从零开始

    iOS block从零开始 在iOS4.0之后,block横空出世,它本身封装了一段代码并将这段代码当做变量,通过block()的方式进行回调. block的结构 先来一段简单的代码看看: void ...

  5. iOS Crash文件的解析

    iOS Crash文件的解析 开发程序的过程中不管我们已经如何小心,总是会在不经意间遇到程序闪退.脑补一下当你在一群人面前自信的拿着你的App做功能预演的时候,流畅的操作被无情地Crash打断.联想起 ...

  6. ios Block详细用法

    ios Block详细用法 ios4.0系统已开始支持block,在编程过程中,blocks被Obj-C看成是对象,它封装了一段代码,这段代码可以在任何时候执行.Blocks可以作为函数参数或者函数的 ...

  7. [转载]iOS 10 UserNotifications 框架解析

    活久见的重构 - iOS 10 UserNotifications 框架解析 TL;DR iOS 10 中以前杂乱的和通知相关的 API 都被统一了,现在开发者可以使用独立的 UserNotifica ...

  8. IOS的XML文件解析,利用了NSData和NSFileHandle

    如果需要了解关于文档对象模型和XML的介绍,参看 http://www.cnblogs.com/xinchrome/p/4890723.html 读取XML 上代码: NSFileHandle *fi ...

  9. iOS学习——JSON数据解析(十一)

    在之前的<iOS学习——xml数据解析(九)>介绍了xml数据解析,这一篇简单介绍一下Json数据解析.JSON 即 JavaScript Object Natation,它是一种轻量级的 ...

随机推荐

  1. linux基本知识0

    linux的基本原则: 1.有目的单一的小程序组成,组合小程序完成复杂任务. 2.一切皆文件 3.尽量避免捕获用户接口 4.配置文件保存为纯文本格式 CLI接口: 命令提示符,prompt,bash ...

  2. 【原】移动web滑屏框架分享

    本月26号参加webrebuild深圳站,会上听了彪叔的对初心的讲解,“工匠精神”这个词又一次被提出,也再次引起了我对它的思考.专注一个项目并把它做得好,很好,更好...现实工作中,忙忙碌碌,抱着完成 ...

  3. vs2013 error : cannot open source file "SDKDDKVer.h"

    改: 项目属性--常规--工具集--Visual Studio 2013-WindowsXP(v120_xp)

  4. 00 Cadence学习总目录

    这个系列是我学习于博士CADENCE视频教程60讲时,一边学一边记的笔记.使用的CADENCE16.6. 01-03课 了解软件 创建工程 创建元件库 分裂元件的制作方法 04课 正确使用hetero ...

  5. 4种解决json日期格式问题的办法

    4种解决json日期格式问题的办法   开发中有时候需要从服务器端返回json格式的数据,在后台代码中如果有DateTime类型的数据使用系统自带的工具类序列化后将得到一个很长的数字表示日期数据,如下 ...

  6. [LeetCode] Water and Jug Problem 水罐问题

    You are given two jugs with capacities x and y litres. There is an infinite amount of water supply a ...

  7. 基于C/S架构的3D对战网络游戏C++框架 _【不定期更新通知】

    由于笔者最近有比赛项目要赶,这个基于C/S架构的3D对战网络游戏C++框架也遇到了一点瓶颈需要点时间沉淀,所以近一段时间不能保证每天更新了,会保持不定期更新.同时近期笔者也会多分享一些已经做过学过的C ...

  8. jquery-leonaScroll-1.3-自定义竖向自适应滚动条插件

    下载链接地址:https://share.weiyun.com/9ac3ca3fb29648bb1aad1b83a76b123c (密码:4y9t)[含mini版] 欢迎使用leonaScroll-1 ...

  9. SQL基础语法(三)

    SQL WHERE 子句 WHERE 子句用于规定选择的标准. WHERE 子句 如需有条件地从表中选取数据,可将 WHERE 子句添加到 SELECT 语句. 语法SELECT 列名称 FROM 表 ...

  10. 常用jQuery 方法

    //强制给数字补全小数点 function toDecimal2(x) { var f = parseFloat(x); if(isNaN(f)) { return false; } var f = ...