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程序包管理之yum及源代码安装

    第十六章.Linux程序包管理之yum及源代码安装 目录 yum介绍 yum配置文件 yum的repo配置文件中可用的变量 yum命令的使用 使用光盘作为本地yum仓库 如何创建yum仓库 编译安装的 ...

  2. 腾讯云CentOS系统配置apache和tomcat

    本文使用yum软件包管理工具基于CentOS7.2版本配置apache和tom. 云服务器选购完毕后,安装Xshell软件,输入用户名密码即可远程登陆登录(centos用户名默认是root). 1,下 ...

  3. Ubuntu 14.04 LTS下安装Google Chrome浏览器

    在Ubuntu 14.04下安装Google Chrome浏览器非常简单,只要到Chrome的网站下载Deb安装包并进行安装即可.当然你也可以使用APT软件包管理器来安装Google Chrome浏览 ...

  4. Execl数据导入sql server方法

    在日常的程序开发过程中,很多情况下,用户单位给予开发人员的数据往往是execl或者是access数据,如何把这些数据转为企业级是数据库数据呢,下面就利用sqlserver自带的功能来完成此项任务. 首 ...

  5. 开发管理系统时,安装sqlserver2005问题整理

    最近在为单位开发一个综合管理系统.但是由于时间的问题,有时候就把程序带回家进行修改.但是家里有没有环境,就把数据库文件和程序带回家,可是随之问题来了.要重新在家里陪着开发环境,vs2008非常快的就安 ...

  6. knockout学习笔记10:demo

    前面已经介绍了ko的基本用法,结合官方文档,基本就可以实际应用了.本章作为ko学习的最后一篇,实现一个简单的demo.主要集中在ko,所以后台数据都是静态的.类似于博园,有一个个人文章的分类列表,一个 ...

  7. python读取excel一例-------从工资表逐行提取信息

    在工作中经常要用到python操作excel,比如笔者公司中一个人事MM在发工资单的时候,需要从几百行的excel表中逐条的粘出信息,然后逐个的发送到员工的邮箱中.人事MM对此事不胜其烦,终于在某天请 ...

  8. 服务端跨域处理 Cors

    1  添加 System.Web.Cors,System.Web.Http.Cors 2 global文件中 注册asp.net 管道事件 protected void Application_Beg ...

  9. 语义网 (Semantic Web)和 web 3.0

    语义网=有意义的网络. "如果说 HTML 和 WEB 将整个在线文档变成了一本巨大的书,那么 RDF, schema, 和 inference languages 将会使世界上所有的数据变 ...

  10. UDP Server

    //UDP服务器端程序,可以接受广播,不可接受多播,多播需要join播地址@Override public void run() { while (true) { try { DatagramSock ...