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. Js IP转数字

    <script type="text/javascript"> function d2h(d) { return d.toString(16) } function h ...

  2. String构造器中originalValue.length>size 发生的情况

    最近在看Jdk6中String的源码的时候发现String的有个这样的构造方法,源代码内容如下: public String(String original) { int size = origina ...

  3. php在5.5.0默认提供了Zend OPcache

    eaccelerator无法兼容php5.5.0,好在php在5.5.0默认提供了Zend OPcache,所以一直习惯eaccelerator的朋友如果要升级到php5.5.0的话,可能要暂时和ea ...

  4. app开发项目简单的结构一

    一 .Network (网络) 1. 接口类(可以一个放所有接口的头文件)ApiConfig.h. (1). 可以放服务器的地址.图片服务器的地址及其它接口的地址(这样做的好处是只用导入一个头文件即可 ...

  5. Why many EEG researchers choose only midline electrodes for data analysis EEG分析为何多用中轴线电极

    Source: Research gate Stafford Michahial EEG is a very low frequency.. and literature will give us t ...

  6. 值得注意的IsHitTestVisible

    这个属性我们平时可能并不怎么用.先来看下MSDN上的解释: 解释的非常专业,然而我并没有看懂. 说说我的理解吧:把这个属性设置为false,看起来没有变化,但操作上已经把他完全忽视了,不触发事件,可以 ...

  7. 使用SharpPCap在C#下进行网络抓包

    在做大学最后的毕业设计了,无线局域网络远程安全监控策略那么抓包是这个系统设计的基础以前一直都是知道用winpcap的,现在网上搜了一下,有用C#封装好了的,很好用下面是其中的几个用法这个类库作者的主页 ...

  8. beanstalkd 消息队列

    概况:Beanstalkd,一个高性能.轻量级的分布式内存队列系统,最初设计的目的是想通过后台异步执行耗时的任务来降低高容量Web应用系统的页面访问延迟,支持过有9.5 million用户的Faceb ...

  9. sql server 多列转多行实现方法

    select * from b_workOrder select * from( SELECT work_order_id,work_level, roles,code FROM (SELECT wo ...

  10. 美团大众点评服务框架Pigeon

    服务框架Pigeon架构 • Pigeon提供jar包接入 ,线上运行在tomcat里 • Monitor-CAT ,负责调用链路分析.异常监控告警等 • 配置中心-Lion ,负责一些开关配置读取 ...