一、单例:
1.定义单例类
@interface single : NSObject
@property (nonatomic, copy) NSString *name;
+ (id)shareInstance;
@end
#import "single.h"
static single *instance = nil;
@implementation single
+ (id)shareInstance
{
if (instance == nil) {
instance = [[single alloc] init];
}
return instance;
}
@end
2.实现传值
传值者:
single *s = [single shareInstance];
s.name = _lable.text;
接收者:
//视图将要显示时调用
- (void)viewWillAppear:(BOOL)animated
{
single *s1 = [single shareInstance];
lable.text = s1.name;
}
二、通知:
//取得输入的数据
NSString *text = _textFiekd.text;
NSDictionary *dic = @{
@"key":text
};
//发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"changeValue" object:self userInfo:dic];
[self dismissViewControllerAnimated:YES completion:nil];
//接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAction:) name:@"changeValue" object:nil];
- (void)changeAction:(NSNotification *)notification {
//取得传递的数据
NSDictionary *dic = notification.userInfo;
_label.text = dic[@"key"];
}
三、KVO观察者模式
1.添加观察者
_secondCtrl = [[SecondViewController alloc] init];
//监听secondCtrl的属性值变化
[_secondCtrl addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
//接收到消息后触发的方法
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"change:%@",change);
NSString *text = [change objectForKey:@"new"];
_label.text = text;
}
2.删除观察者
- (void)dealloc
{
[_secondCtrl removeObserver:self forKeyPath:@"happyValue" context:NULL];
}
被观察者
定义观察属性
@property(nonatomic, copy)NSString *text;
赋值
self.text = _textFiekd.text;
四、Block
1.要传值的一边定义block
typedef void(^MyBlock)(NSString *text);
@property(nonatomic, copy)MyBlock block;
@property (weak, nonatomic) IBOutlet UITextField *textFiekd;
_block(_textFiekd.text);
2.接收值的一边
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
secondCtrl.block = ^(NSString *text) {
_label.text = text;
};
}
五、代理
要传值的一边如下配置:
@protocol sendData <NSObject>
- (void)sendData:(NSString *)text;
@end
@property(nonatomic, assign)id<sendData> delegate;
@property (weak, nonatomic) IBOutlet UITextField *textFiekd;
- (IBAction)dismissAction:(id)sender {
[_delegate sendData:_textFiekd.text];
[self dismissViewControllerAnimated:YES completion:nil];
}
接收值的一边如下配置:
@interface ViewController ()<sendData>
@property (weak, nonatomic) IBOutlet UILabel *label;
- (IBAction)presentAction:(id)sender {
SecondViewController *secondCtrl = [[SecondViewController alloc] init];
secondCtrl.delegate = self;
[self presentViewController:secondCtrl animated:YES completion:nil];
}
- (void)sendData:(NSString *)text {
_label.text = text;
}
实现参数传值的几种方式
最新推荐文章于 2019-03-12 11:05:58 发布