<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">iOS开发中一般有四种传值方式,分别是:</span>
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">属性传值;</span>
代理传值;
block传值;
单例传值;
属性传值是最简单,也是最常用的从前往后传值方式。例如,ApushB,同时将A中的一些值传到B使用,一般给B增加一些属性(字典,集合,数组),在push的时候,将B的属性值传过去,B就可以使用这些值了。
代理传值一般是用来BpopA时使用的,包括block传值也是这样子。
其原理是在B里面定义代理和block,然后在A里实现,通过在A实现的时候,利用代理或者block定义时在B里调用的时候,传过来的参数,A可以获取B的值。
而单例传值则是,在静态区定义一个类的对象,通过每个人对其某个属性的值进行更改,从而实现传值。部分代码如下,demo传到了我的资源里面。
A中的代码:
- (IBAction)SingleTextFPassvalue:(UIButton *)sender {
SingleTon *passValue = [SingleTon shareSingleTonValue];
passValue.passValueStr = _SingleTextF.text;
SecondViewController *secVC = [[SecondViewController alloc]init];
[self.navigationController pushViewController:secVC animated:YES];
}
- (IBAction)blockPassValue:(UIButton *)sender {
SecondViewController *secVC = [[SecondViewController alloc]init];
secVC.passValue = ^(NSString* str){
self.blockTextF.text = str;
};
[self.navigationController pushViewController:secVC animated:YES];
}
- (IBAction)delegatePassValue:(UIButton *)sender {
SecondViewController *secVC = [[SecondViewController alloc]init];
secVC.delegate = self;
[self.navigationController pushViewController:secVC animated:YES];
}
-(NSString *)passValue{
return self.delegateTextF.text;
}
B中的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
SingleTon *value = [SingleTon shareSingleTonValue];
self.singleTonPassValue.text = value.passValueStr;
// __weak SecondViewController *my_self = self;
// my_self.passValue = ^(NSString *str){
// self.blockvalue.text = str;
// };
// self.blockvalue.text = self.passValue();
if(self.delegate && [self.delegate respondsToSelector:@selector(passValue)]){
self.delegateValue.text = [self.delegate passValue];
}
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
[self.navigationItem setLeftBarButtonItem:buttonItem];
}
-(void)backAction{
self.passValue(self.blockvalue.text);
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
第一;block的修饰词用copy;
第二:在自身使用block的时候,为了防止循环应用,通常用如下方式:
//block的循环引用,有可能会造成内存泄露
//当block是self的一个属性的时候,我们在block实现体内需要使用到self的时候,有可能会造成循环引用,导致的结果为self的引用计数有可能为2,释放不掉,造成内存泄露。所以我们需要使用__weak关键字来修饰self对象,让该对象在block实现体内不需要内存管理。这个时候引用计数也就不会增加。//在ARC下使用__weak,在MRC下使用__block修饰。
__weak RootViewController *my_self = self;
self.circleBlock = ^(){
my_self.navigationItem.title = @"aaa";
};