标签:
今天分享一下页面之间传值的几种方式
1、@property属性
这个不用多说了吧,当页面A 跳转到页面B,在class B中声明属性
@property (nonatomic, copy) NSString *name;
初始化B
FirstViewController *firstVC = [FirstViewController new]; firstVC.name = @"name"; [self presentViewController:firstVC animated:YES completion:nil];
2、Delegate
当页面A 跳转到页面B,B页面返回时传值给A,可以这样实现,在class B中定义一个@protocol,并声明属性delegate;
#import <UIKit/UIKit.h> @protocol FirstViewControllerDelegate <NSObject> - (void)print; @end @interface FirstViewController : UIViewController @property (nonatomic, assign) id<FirstViewControllerDelegate> delegate; @end.m文件
- (void)backClick:(UIButton *)sender
{
[self dismissViewControllerAnimated:YES completion:^{
if ([self.delegate respondsToSelector:@selector(print)]) {
[self.delegate print];
}
}];
}页面A .m实现,要继承FirstViewController的代理
- (void)buttonClicked:(UIButton *)sender
{
FirstViewController *firstVC = [FirstViewController new];
firstVC.delegate = self;
[self presentViewController:firstVC animated:YES completion:nil];
}
#pragma mark - FirstViewControllerDelegate
- (void)print
{
NSLog(@"delegate response");
}3、Block
当页面A 跳转到页面B,B页面返回时传值给A,可以这样实现,在class B中定义一个block,并声明属性block
#import <UIKit/UIKit.h> typedef void (^FirstViewControllerBlock)(NSString *str); @interface FirstViewController : UIViewController @property (nonatomic, copy) FirstViewControllerBlock block; @end.m文件
- (void)backClick:(UIButton *)sender
{
self.block(@"first block");
[self dismissViewControllerAnimated:YES completion:nil];
}页面A .m实现
- (void)buttonClicked:(UIButton *)sender
{
FirstViewController *firstVC = [FirstViewController new];
[self presentViewController:firstVC animated:YES completion:nil];
firstVC.block = ^(NSString *str) {
NSLog(@"str is: %@", str);
};
}
4、NSNotification
标签:
原文地址:http://blog.csdn.net/qq510304723/article/details/46380219