[OC] Block的使用

  由ControllerA跳转到controllerB,在controllerB中选择一个参数的值,并将它传回给controllerA。

  首先,在controllerB的.h文件中写入:

@interface ViewControllerB :UIViewController

//定义一个block,返回值的参数类型为 id ,名称为VCBBlock
typedef  void(^VCBBlock)(id);

//声明一个上一行定义的block,这个实例化的block的名字叫做“exampleOfABlock”
@property(nonatomic,copy)VCBBlock  exampleOfVCBBlock;

@end

  接着在controllerB的.m文件中写入:

whenSomethingHappened  {

//我们选择了一个值
NSString  *string = @"信息";

//将这个值传回给之前的界面
self.exampleOfVCBBlock(string);

}

  接下来,在controllerA的.m文件中import "controllerB.h"

  然后在继续在A的.m文件中写入:

whenSomethingHappened {

//跳转到controllerB
ViewControllerB  *vc =[ [ ViewControllerB  alloc ] init ];
[ self.navigationController  pushViewController: vc  animated : YES];

vc.exampleOfVCBBlock =  ^( id  * str ) {    //参数回调,接收在B中选择的类型为id的值
//在这里可以写入对传回的值的操作,比如 NSLog(str); };
posted @ 2016-09-11 15:02  Oran  阅读(206)  评论(0编辑  收藏  举报