一般来说有以下几种方式进行传值:
1.委托代理(delegate)
2.通知notification方式
3.Block方式
4.UserDefault或者文件形式
5.单例模式方式
6.属性传值
下面分情形对几种传值方式进行说明:
(1).从A页面跳转到B页面
方法:在B页面控制器中设置一个属性,在A页面跳转至B页面的时候,将B的属性赋值即可
@property(nonatomic) NSInteger flag;
- (IBAction)showSecondView:(id)sender { SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; second.delegate = self; second.flag = 0; [self presentViewController:second animated:YES completion:nil]; }
(2).A页面跳转到B页面,B页面再跳转到A页面
解决办法1:使用delegate进行传值。例子如下:
设置协议和方法:
//SecondViewController.h @protocol secondViewDelegate -(void)showName:(NSString *)nameString; @end
@interface SecondViewController : UIViewController @property (nonatomic, weak)id<secondViewDelegate> delegate; @property (nonatomic, copy) ablock block; @end
//SecondViewController.m - (IBAction)delegateMethod:(id)sender { if ([self notEmpty]) { [self.delegate showName:self.nameTextField.text]; [self dismissViewControllerAnimated:YES completion:nil]; }else{ [self showAlert]; } }
//RootViewController.m -(void)showName:(NSString *)nameString{ self.nameLabel.text = nameString; }
记得要设置delegate的指向!
解决方法2:使用通知机制
在B控制器中发送通知:
//SecondViewController.m - (IBAction)notificationMethod:(id)sender { if ([self notEmpty]) { [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeNameNotification" object:self userInfo:@{@"name":self.nameTextField.text}]; [self dismissViewControllerAnimated:YES completion:nil]; }else{ [self showAlert]; } }
在A控制器中注册通知:
//RootViewController.m - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeNameNotification:) name:@"ChangeNameNotification" object:nil]; }
记得在不使用的时候一定要移除通知,不然会造成内存泄露
//RootViewController.m -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }
调用显示:
//RootViewController.m -(void)ChangeNameNotification:(NSNotification*)notification{ NSDictionary *nameDictionary = [notification userInfo]; self.nameLabel.text = [nameDictionary objectForKey:@"name"]; }
解决方法3:使用Block去实现
在B控制器中内定义一个Block,参数为string
typedef void (^aBlock)(NSString *str) @property(nonamatic,copy) aBlock block;
在B控制器中:
- (IBAction)blockMethod:(id)sender { if ([self notEmpty]) { if (self.block) { self.block(self.nameTextField.text); [self dismissViewControllerAnimated:YES completion:nil]; } }else{ [self showAlert]; } }
在A视图显示,回调Block
- (IBAction)showSecondWithBlock:(id)sender { SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; [self presentViewController:second animated:YES completion:nil]; second.block = ^(NSString *str){ self.nameLabel.text = str; }; }
单例模式传值的话,感觉有那么点别扭,这里就不作介绍啦!