iOS-Block总结 && 全面解析逆向传值

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,异步下载一张图片,并在主线程中显示)
          调用方:
                       定义块代码属性
[objc] view plain copy
  1. #import <Foundation/Foundation.h>  
  2.   #import <UIKit/UIKit.h>  
  3.   
  4.   @class YSCNSOperationOP;  
  5.   
  6.   typedef void(^setUpUIImage)(YSCNSOperationOP *);  
  7.   
  8.   @interface YSCNSOperationOP : NSOperation  
  9.   
  10.   @property (nonatomic, copy) NSString *urlString;  
  11.   @property (nonatomic, strong) UIImage *image;  
  12.   
  13.   @property (nonatomic, copy) setUpUIImage myBlock;  
  14.   - (void)setUpUIImage:(setUpUIImage )block;  
  15.   
  16.   @end  

在适当的时候执行:   
[objc] view plain copy
  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.   
  14.        NSURL *url = [NSURL URLWithString:urlString];  
  15.        NSData *data = [NSData dataWithContentsOfURL:url];  
  16.        UIImage *image = [UIImage imageWithData:data];  
  17.        return image;  
  18.    }  
  19.    - (void)setUpUIImage:(setUpUIImage )block {  
  20.        if (block) {  
  21.            self.myBlock = block;  
  22.        }  
  23.    }  
  24.    @end  

     被调用方:
                         准备代码块:
 
[objc] view plain copy
  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)在需要的时候通知代理;‘
   
举例
                     委托方:定义协议;
                                      代理属性;
 
[objc] view plain copy
  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  

在需要的时候通知代理:
[objc] view plain copy
  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  

                         代理方:
[objc] view plain copy
  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  

        二、通知:
                    通知方:注册通知;
                    观察者:注册观察者;
                                   移除观察者对象;
               
                     举例:
                    通知方注册通知、并在恰当的时候发出通知:
[objc] view plain copy
  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.   
  14.     NSURL *url = [NSURL URLWithString:urlString];  
  15.     NSData *data = [NSData dataWithContentsOfURL:url];  
  16.     UIImage *image = [UIImage imageWithData:data];  
  17.     return image;  
  18. }  
  19. @end  
 
 
           观察者:注册观察者、移除观察者
[objc] view plain copy
  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 
原文地址:https://www.cnblogs.com/it-k-50/p/6120189.html