Block传值

1.1  Block内部写方法,其声明和实现部分:   

#import <Foundation/Foundation.h>

 //重定义

typedef void (^String)(NSString *); 

@interface AppTool : NSObject 

- (void)sendNumber:(NSInteger)number andBlock:(String)block;//Block类型作为参数使用 

@end

//  .m 实现的部分的

#import "AppTool.h" 

@implementation AppTool 

- (void)sendNumber:(NSInteger)number andBlock:(String)block{    

    NSString *string = [NSString stringWithFormat:@"%ld",number];//实现了吧数值转化为字符串

    block(string);//把字符作为Block的参数

}

@end

1.2  具体使用(Block传值):

   //首先实例化一个对象

    AppTool *tool = [[AppTool alloc] init];

    //使用声明好的方法,实现赋值

    [tool sendNumber:10086 andBlock:^(NSString *str) {

        self.label.text = str;

    }];

2.1  Block传值的使用(Block传值和协议传值非常像): //secondController的内部的写法

//   .h  内部的声明部分

typedef void (^StringC)(NSString *,UIColor *);//冲定义

@interface SecondViewController : UIViewController

@property (nonatomic, copy) StringC stringC;//一定要使用 copy

@end

//   .m  内部的实现部分

 //和协议的使用相似

    if(self.stringC != nil){

        self.stringC(self.field.text,self.view.backgroundColor);//传值是 field的内容和背景颜色。。和函数的使用相似

    }

2.2  具体的实现赋值(在接收数值的界面 实现Block)

secondController.stringC = ^(NSString *str, UIColor *color){  

        self.label.text = str;

        self.view.backgroundColor = color;

    }; //实现了传值给 self 的内部控件 

原文地址:https://www.cnblogs.com/jiurong001/p/5198717.html