IOS三种传值方式
2016-03-09 13:41
381 查看
将“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];
}
相关文章推荐
- iOS 滑动删除cell
- iOS inline
- iOS内存警告的等级
- iOS证书描述文件说明
- iOS学习笔记——AutoLayout的约束
- [置顶] 【iOS开发】Xcode证书问题报错解决方案集锦
- ios 计算月数、周数、天数
- iOS textfield 键盘弹出后不能切换中文键盘
- [绍棠] 定制iOS 中的导航栏和状态栏
- ios 3D Touch功能的实现
- 如何用代码控制以不同屏幕方向打开新页面【iOS】
- XPC connection interrupted in Xcode 7 for iOS 9
- 【Xamarin挖墙脚系列:Xamarin.IOS的多个Storybord分隔视图的导航】
- ios8中百度推送接收不到
- iOS中用户未登录状态下点击下方tabBar触发登录
- iOS中使用RSA对数据进行加密解密
- ios之block
- NSString转换为char* char*转换为NSString
- iOS 引导用户到系统设置开启定位 访问照片 话筒 相册 相机
- iOS开发中弹窗的方式