IOS三种传值方式
来源:互联网 发布:反淘宝 编辑:程序博客网 时间:2024/06/04 20:01
将“A“ VC中的值传到”B“VC中
一、协议
1、创建一个协议(protocol)2、在A中声明协议
@property (nonatomic,assign)id <SendBackMsg> bDelegate;
3、在A中调用协议:
- (IBAction)goBackBtn:(UIButton *)sender {
if (self.bDelegate && [self.bDelegate respondsToSelector:@selector(sendMsgWithName:andPwd:)]) {
[self.bDelegate sendMsgWithName:self.redNameTF.text andPwd:self.redPwdTF.text];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
4、在B中实现协议、初始化协议
//实现协议方法
-(void)sendMsgWithName:(NSString *)aName andPwd:(NSString *)aPwd
{
self.welcomeLb.text = [NSString stringWithFormat:@"欢迎,%@,%@",aName,aPwd];
}
//初始化
self.redVC.aDelegate = self;
二、代码块(block)
1、进行代码块定义,定义在A.h中,typedef void(^SendMsg)(NSString *,NSString *);//声明
@property (nonatomic,strong) SendMsg aBlock;
2、进行代码块调用在A.m中
self.aBlock(self.blueNameTF.text,self.bluePwdTF.text);
3、在B.m中进行代码块实现
//防治block引用self(防止循环引用)
// __weak HomeViewController *weakSelf = self;
__unsafe_unretained HomeViewController *weakSelf = self;
self.blueVC.aBlock = ^(NSString *aName,NSString *aPwd){
NSLog(@"代码块的实现");weakSelf.welcomeLb.text = [NSString stringWithFormat:@"代码块方式:%@,%@",aName,aPwd];
};
三、通知
1、在A.m中创建通知:NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.greenNameTF.text,@"name",self.greenPwdTF.text,@"pwd", nil];
//创建通知
NSNotification *notifacation = [NSNotification notificationWithName:@"MSG" object:self userInfo:dic];
//获取通知
[[NSNotificationCenter defaultCenter]postNotification:notifacation];
2、在b.m中注册通知
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.welcomeLb.text = [NSString stringWithFormat:@"欢迎你,%@,%@",[self.infoDict objectForKey:@"name"],[self.infoDict objectForKey:@"password"]];
//注册通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomething:) name:@"MSG" object:nil];
}
//———---
-(void)doSomething:(NSNotification *)notificat
{
NSDictionary *infoDict = notificat.userInfo;
NSString *aName = [infoDict objectForKey:@"name"];
NSString *aPwd = [infoDict objectForKey:@"pwd"];
self.nameTf.text = aName;
self.pwdTf.text = aPwd;
}
3、销毁通知
-(void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"BlueSendMsg" object:nil];
}
1 0
- IOS三种传值方式
- ios:协议、闭包、通知三种传值方式
- iOS NSString 连接方式
- IOS Socket 同步方式
- iOS 页面跳转方式
- iOS 各种动画方式
- ios常见存储方式
- iOS 跳转的方式
- ios 注册打开方式
- IOS多线程实现方式
- IOS JSON解析方式
- iOS下载方式详解
- ios 传值方式
- IOS存储方式
- ios中几种传值方式
- ios中五种回调方式
- ios图片拉升几种方式
- IOS中几种传值的方式
- 页面增加定时器
- GitHub Top 100的Android开源库
- java并发编程(一):计数器
- 时域反射计TDR原理
- Matlab提示Could not find the compiler cl on the DOS path
- IOS三种传值方式
- HDOj1016 Prime Ring Problem
- 碎片的最佳实践——一个简易版的新闻应用
- ViewPager+Fragment 常使用懒加载
- C#中冒泡排序和比较排序
- 启动tomcat报,这个怎么弄啊,我这包不冲突
- Softmax回归原理简介
- 跟着项目学javaweb(std):3(走进后台)
- java笔试题(二)