心得:
笔者感言:解决问题的根本途径,在于知识的灵活运用,你运用的越灵活,所能解决的问题就越多,有人说,有些东西都只是最基础的,不没什么卵用。我想说的是,没什么用,你还学他干嘛,大家还学他干嘛。对于这类人,不想多说什么,我用老子的一句话表达我的观点:天下难事必起于易,简单的东西灵活运用多了,相对而言就难了,在有些人严重,也就有用了,但是一定不能舍弃基础,学到的东西,一定想着去用它,如果不想着去用它,那你费那个时间去学它干嘛?不能想着,为解决一种需求,而寻求某种特定的解决方法,要想着,当你找到一种解决某一问题的方法时,去思考,这个方法,还能解决什么问题?或者说,我再改进这个方法,它又能解决什么问题。
block简单理解,就是一段匿名的代码块,是具有某种功能的代码块。使用block,更多的是为了两个页面之间的传值。
有些时候,两个页面之间传值,使用其它方法,会导致两者,循环引用,因此,一些特殊的传值方式就产生了。而block使用起来,更加灵活,更加方便。
下面已一个简单的例子看一下,他们之间的传值,页面A点击按钮,跳转到页面B,然后把页面B中的值传入到A中。
ViewController.m文件
#import "ViewController.h"
#import "NewViewController.h"
@interface ViewController ()
{
NSString *text;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blueColor];
//创建一个button按钮,实现视图跳转功能
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 100, 100, 100);
button.backgroundColor = [UIColor greenColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(getPress) forControlEvents:UIControlEventTouchUpInside];
}
- (void)getPress{
NewViewController *view = [[NewViewController alloc]init];
[self presentViewController:view animated:YES completion:^{
}];
//得到页面B中的block,获取到B页面中的参数
[view setMyBlock1:^(NSString *a) {
NSLog(@"%@",a);
}];
//得到页面B中的block,获取参数,并传入返回值
[view setMyBlock2:^int(NSString *b)
NSLog(@"%@",b);
//传入返回值,可以再B页面中使用
return 998
}];
}
NewViewController.h文件中
#import <UIKit/UIKit.h>
@interface NewViewController : UIViewController
//有参数,无返回值
@property(nonatomic,copy)void (^myBlock1)(NSString *a);
//有参数,有返回值
@property(nonatomic,copy)int (^myBlock2)(NSString *b);
@end
NewViewController.m文件中
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
//创建一个button按钮,实现视图跳转功能
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 100, 100, 100);
button.backgroundColor = [UIColor greenColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(press) forControlEvents:UIControlEventTouchUpInside];
}
//button的点击事件
- (void)press{
NSString *b = @"小龙女";
//要传的参数,放入到block中
_myBlock1(b);
NSString *c = @"杨过";
int count;
//接收返回值,并传入参数
count = _myBlock2(c);
NSLog(@"count = %d",count);
[self dismissViewControllerAnimated:YES completion:^{
}];
}
心得:从上面可以看出,block可以双向传值,即说的回调。
我个人理解,传值可以分为两种,一是正向传值,二,是逆向传值。
以上面两个视图为例,A页面可以present到B页面,若从A传值到B,则可以理解为正向传值,这种传值,方法较多,也比较简单。
而,要想从B页面中传值到A,一些方法,会导致循环引用,这时使用block,比较简单便捷。我理解为它为逆向传值。当然,还有其它许多传值方式,如代理,通知,kvo。