常用的传值方式
很久没发博客了,小编在此深表歉意,一是因为抽不出时间,二是因为比较懒,呵呵,总之很久没写博客了。今天就写一遍关于几种常见的传值方式吧,个人见解,有问题请及时评论。
传值方式有多种,小编自己常用的也就那么几种,但是这几种已经可以实现传值的目的了,主要是属性传值、代理传值、block传值、单例传值、通知传值。下面分别来说说是怎么实现的。
(1) 属性传值,这个相对就很简单了。就是从上个界面往下个界面传值,就用这个,也不多说哒。
除了属性传值,其他几种一般是从后面的界面往前面的传的。
(2)代理传值
代理是个名词,就是你要让别人帮你做事情。两个controller,一个是A,一个是B,B要在回到A的时候把值传给A,首先它自己要在.h声明代理方法。
@protocol SeconviewDelegate <NSObject>
-(void)initWithSentToString:(NSString *)str;
@end
@interface SeconViewController : UIViewController
@property(nonatomic,weak)id<SeconviewDelegate>delegate;
@end
在返回的时候就把值传过去,主意:这里self .delegate小编第一次写成了self,就没值,得细心啊
if (self.delegate && [self.delegate respondsToSelector:@selector(initWithSentToString:)]) {
[self.delegate initWithSentToString:self.fied.text];
}
[self.navigationController popViewControllerAnimated:YES];
此时,回到了A界面,指定代理对象
-(void)buttonPress:(UIButton *)sender
{
B * b = [B alloc]init];
b.delegate = self;
[self.navigationController pushViewController:b animated:YES];
}
代理的方法已经把值带过来了,此处该有掌声,因为你的目的已经达到了
#pragma mark --deleget methrod
-(void)initWithSentToString:(NSString *)str
{
NSLog(@"%@----",self.label.text);
}
(3)block传值 对于block本人开始是抵触 的,因为用它的地方太少,所以有畏惧感,但是用了之后发现确实很好用,也是现在的潮流啊。对block这块,涉及到的东西比较多,还得多看看这方面的。好吧,开始干。
第一步,在B的。h文件里定义block,block传值不要返回值,故
@property(nonatiomic,strong) void(^MyBlock)(NSString *str);
第二部:在。m里进行传值
-(void)buttonPress:(UIButton *)sender
{
if(_MyBlock)
__MyBlock = (@"111");
}
第三部:回到了A界面
-(void)buttonpress:(UIButton *)sender
{
SeconViewController *sec = [[SeconViewController alloc]init];
__weak __typeof(self)weakSelf = self; //这是这里的重点1
sec.MyBlock = ^(NSString *str){
__strong __typeof(self)strongSelf = weakSelf; //这是这里的重点2
strongSelf.label.text = str;
NSLog(@" str %@",str)
};
[self.navigationController pushViewController:sec animated:YES];
} ok,到了此处就finish了。