代码块 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
- 代码块 block 传值
- BLOCK代码块
- iOS 代码块Block
- block代码块
- C21_OC11-block代码块
- block代码块 小结
- OC代码块block
- Block代码块分析
- 代码块block
- 代码块(Block)
- 代码块(block)
- 代码块block
- iOS block代码块
- iOS代码块Block
- Objective-C block(代码块)
- Objective-C - 代码块block
- 【Objective-C】代码块(Block)
- 简单易学代码块(block)
- 数据结构 C语言实现冒泡排序
- VMware虚拟机PXE安装RHEL6.4
- TelephonyManager类,获取手机和sim卡信息接口
- codeforces 515B B. Drazil and His Happy Friends(模拟)
- 红黑树算法以及TreeMap实现原理
- 代码块 block 传值
- Gson解析json数组
- aauto学习系列之<9>函数2
- C#程序中调用cmd执行命令
- OC产生随机数的几种方法
- Java内部类详解
- hdu5399(计数)
- 九度OJ 题目1073:杨辉三角形
- Android cookies正确的更新方式