代码块 block 传值

来源:互联网 发布:叮当软件制作教程 编辑:程序博客网 时间:2024/06/05 06:01

不知道这样理解对不对   
定义block并调用block的类(类2)是以block中的参数把值传出去,而实现block代码的类(类1)是获取了其参数,并实现其他用途。如果block有返回值,则类1实现时有返回值,而类2的代码中又可调用其返回值实现其他用途。


类1:

#import <UIKit/UIKit.h>@interface ViewController : UIViewController@end


#import "ViewController.h"#import "SecondViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UIButton *btn;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (IBAction)goToAnotherView:(UIButton *)sender {    SecondViewController *sVC=[[SecondViewController alloc]init];    sVC.myBlock=^(NSString*txt)    {//实现block,获取了类2传过来的txt值        self.btn.titleLabel.text=txt;    };    sVC.myReturnBlock=^(NSInteger num)    {//        NSInteger i=10*num;        return [NSString stringWithFormat:@"%ld",10*num];  //返回值,可被类2使用    };    [self.navigationController pushViewController:sVC animated:YES ];    }@end


类2

#import <UIKit/UIKit.h>@interface SecondViewController : UIViewController@property (nonatomic, strong) void (^myBlock)(NSString *text);  //定义block@property (nonatomic, strong) NSString* (^myReturnBlock)( NSInteger num);@end

#import "SecondViewController.h"@interface SecondViewController ()@property (strong, nonatomic)  UITextView *textV;@end@implementation SecondViewController- (void)viewDidLoad {    [super viewDidLoad];    self.view.backgroundColor=[UIColor whiteColor];    _textV=[[UITextView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)];    _textV.backgroundColor=[UIColor yellowColor];    _textV.text=@"why";    [self.view addSubview:_textV];        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 250, 60, 30)];    btn.backgroundColor=[UIColor purpleColor];    [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:btn];}-(void)click{    self.myBlock(self.textV.text);  //调用block    NSInteger i=7;    NSString* j=self.myReturnBlock(i);    NSLog(@"%@",j);    [self.navigationController popViewControllerAnimated:YES];}@end


0 1
原创粉丝点击