IOS 成功失败的Block写法


基本思路跟上篇一致。  只是此处将成功与失败给封装起来了。这样做的好处在于,比如说用到百度地图定位,成功的话进成功的Block方法,失败的话进失败的Block方法。

代码如下:

A页面头文件(定义Block,初始化Block):


- (void)launchSuccessBlock:(successBlock)successBlock launchFailure:(failBlock)failureBlock (成功与失败的集合方法)


typedef void(^successBlock)(NSString *showText);

typedef void (^failBlock)();


@interface CHAddressListViewController : CHBaseViewController

@property (nonatomic,strong) successBlock testSuccessBlock;
@property (nonatomic,strong) failBlock testFailBlock;

//测试下block
- (void)launchSuccessBlock:(successBlock)successBlock launchFailure:(failBlock)failureBlock;

@end

A页面实现文件(传值给B页面):

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    //即将消失的时候
    
    if (self.returnTextBlock !=nil)
    {
        self.returnTextBlock(@"block 传值测试");
        
        NSLog(@"======%@=======",self.returnTextBlock);
    }
    
    //此处简单的直接赋值,倘若在实际使用中,可以在百度地图的定位成功中调用
    if (self.testSuccessBlock != nil)
    {
        self.testSuccessBlock(@"block 测试成功");
    }
    
    //可以在百度地图的定位失败中调用
    if (self.testFailBlock != nil)
    {
        self.testFailBlock(@"block 测试失败");
    }
}

//Block回调
- (void)launchSuccessBlock:(successBlock)successBlock launchFailure:(failBlock)failureBlock
{
    self.testSuccessBlock = successBlock;
    self.testFailBlock = failureBlock;
}


B页面实现页面(获取从页面传过来的Block值)

@implementation secondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initContent];
}

- (void)initContent
{
    _label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, (kDEVICEWIDTH - 100), 30)];
    _label.backgroundColor = [UIColor grayColor];
    _label.textColor = [UIColor yellowColor];

    [self.view addSubview:_label];
    
    
    UIButton *_commitBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 179, kDEVICEWIDTH-30, 45)];
    _commitBtn.backgroundColor = [UIColor grayColor];
    [_commitBtn addTarget:self action:@selector(commitClick) forControlEvents:UIControlEventTouchUpInside];
    [_commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    _commitBtn.titleLabel.textColor = [UIColor whiteColor];
    _commitBtn.layer.cornerRadius = 4;
    [self.view addSubview:_commitBtn];

    _viewConTroller = [[CHAddressListViewController alloc] init];
    
    [_viewConTroller returnText:^(NSString *showText)
    {
             CHDebugLog(@"---------%@------------",showText);
             // self.secTextField.text = showText;
    
            // _label.text = showText;
    }];
    
    
    [_viewConTroller launchSuccessBlock:^(NSString *showtext)
     {
         //CHDebugLog(@"---------Success Launch Block------------");
         CHDebugLog(@"---------Block Success Value :%@------------",showtext);
         
         _label.text = showtext;
     }
    launchFailure:^{
    
        CHDebugLog(@"---------fail Launch Block------------");
    }];
};




你可能感兴趣的:(IOS 成功失败的Block写法)