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