Block传值
2017-05-24 本文已影响14人
lovelytitantian
#import <UIKit/UIKit.h>
//无参数
typedef void(^NoReferenceBlock)();
//一个参数
typedef void(^oneReferenceBlock)(NSString *str);
//多个参数
typedef void(^moreReferenceBlock)(NSString *str,NSString *str1);
@interface SecondViewController : UIViewController
@property (nonatomic, copy) NoReferenceBlock noReferenceBlock;
@property (nonatomic, copy) oneReferenceBlock oneReferenceBlock;
@property (nonatomic, copy) moreReferenceBlock moreReferenceBlock;
- (void)noReferenceBlock:(NoReferenceBlock)block;
- (void)oneReferenceBlock:(oneReferenceBlock)block;
- (void)moreReferenceBlock:(moreReferenceBlock)block;
+ (SecondViewController *)secondVC;
@end
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
+ (SecondViewController *)secondVC{
SecondViewController *vc = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
return vc;
}
- (void)noReferenceBlock:(NoReferenceBlock)block{
self.noReferenceBlock = block;
}
- (void)oneReferenceBlock:(oneReferenceBlock)block{
self.oneReferenceBlock = block;
}
- (void)moreReferenceBlock:(moreReferenceBlock)block{
self.moreReferenceBlock = block;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (IBAction)noone:(UIButton *)sender {
if (self.noReferenceBlock != nil) {
self.noReferenceBlock();
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)one:(UIButton *)sender {
if (self.oneReferenceBlock != nil) {
self.oneReferenceBlock(@"一个参数");
}
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)two:(UIButton *)sender {
if (self.moreReferenceBlock != nil) {
self.moreReferenceBlock(@"参数1", @"参数2");
}
[self.navigationController popViewControllerAnimated:YES];
}
#import "ViewController.h"
#import "SecondViewController.h"
SecondViewController *vc = [SecondViewController secondVC];
vc.noReferenceBlock = ^{
NSLog(@"没有参数");
};
vc.oneReferenceBlock = ^(NSString *str) {
NSLog(@"%@",str);
};
vc.moreReferenceBlock = ^(NSString *str, NSString *str1) {
NSLog(@"%@ %@",str,str1);
};
[self.navigationController pushViewController:vc animated:YES];