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. python3: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory

    安装python3遇到报错: wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz ./configure --prefix=/u ...

  2. uva 11059 maximum product(水题)——yhx

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAB1QAAAMcCAIAAABo0QCJAAAgAElEQVR4nOydW7msuhKF2wIasIAHJK

  3. webform Repeater重复器、地址栏传值、Response

    Repeater: 重复器 <HeaderTemplate></HeaderTemplate> - 头模板:在循环开始时,其内容只会打印一遍 <ItemTemplate& ...

  4. [LeetCode] Guess Number Higher or Lower II 猜数字大小之二

    We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...

  5. FineUI(开源版)v4.2.2发布(8年125个版本,官网示例突破300个)!

    开源版是 FineUI 的基石,从 2008 年至今已经持续发布了 120 多个版本,拥有会员 15,000 多位,捐赠会员达到 1,200 多位.   FineUI(开源版)v4.2.2 是 8 年 ...

  6. C#文件帮助类FoderHelper

    using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; us ...

  7. .NET跨平台之旅:成功将示例站点升级至ASP.NET Core RC2

    ASP.NET Core RC2 终于发布了( Announcing ASP.NET Core RC2 ).为了庆祝这次发布,我们将运行在 Ubuntu 服务器上的示例站点 about.cnblogs ...

  8. simpson

    使用二次函数拟合复杂的连续函数求积分 对于(l,r)拟合的积分为(r-l)*(f(l)+4*f((l+r)/2)+f(r))/6 ___________________________ BZOJ217 ...

  9. 【UOJ #35】后缀排序 后缀数组模板

    http://uoj.ac/problem/35 以前做后缀数组的题直接粘模板...现在重新写一下模板 注意用来基数排序的数组一定要开到N. #include<cstdio> #inclu ...

  10. java的字符串截取

    import java.util.Date; import java.text.SimpleDateFormat; Date now = new Date(); def portcodes = new ...