协议、反向传值

  • 总体:
    谁想做什么事,谁就定义协议,并设置一个代理;
    谁想帮做什么事,谁就遵守协议并实现方法。
//
//  SecondVC.h
//  delegate
//
//  Created by yy on 2017/11/17.
//  Copyright © 2017年 zg. All rights reserved.
//
#import <UIKit/UIKit.h>

@class SecondVC;
// 1.自己声明的协议需要遵守<NSObject>协议
// respondsToSelector方法是在<NSObject>协议中声明的方法。
// 不遵守的话,self.delegate失去了<NSObject>协议中的所有方法声明,所以就导致方法不可识别.
@protocol passValueDelegate <NSObject>
@optional
- (void)viewController:(SecondVC*)secondVC passInfo:(id)info;

@end


@interface SecondVC : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *backToFirstVCButton;

// weak修饰,防止循环引用,执行self.delegate = self,引用计数不会加1,在dealloc中会释放;
// strong的话,不会释放,循环引用,内存泄漏
@property (nonatomic,weak)id<passValueDelegate>passDelegate;// 2.定义代理

@end



//
//  SecondVC.m
//  delegate
//
//  Created by yy on 2017/11/17.
//  Copyright © 2017年 zg. All rights reserved.
//

#import "SecondVC.h"

@interface SecondVC ()

@end

@implementation SecondVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.backToFirstVCButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)buttonClick:(UIButton*)sender{
    // 代理对象存在时且可以响应代理,这时,执行代理
    if (self.passDelegate && [self.passDelegate respondsToSelector:@selector(viewController:passInfo:)]) {
        [self.passDelegate viewController:self passInfo:self.textField.text];
    }
    [self dismissViewControllerAnimated:true completion:nil];
}


@end
//
//  ViewController.m
//  delegate
//
//  Created by yy on 2017/11/17.
//  Copyright © 2017年 zg. All rights reserved.
//

#import "FirstVC.h"
#import "SecondVC.h"

@interface FirstVC ()<passValueDelegate> // 遵守协议

@end

@implementation FirstVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.toSecondVCButton addTarget:self action:@selector(toSecond:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)toSecond:(UIButton*)sender{
    SecondVC * secondVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"SecondVC"];
    secondVC.passDelegate = self; // 代理赋值
    [self presentViewController:secondVC animated:true completion:nil];

}

// 实现代理的方法
- (void)viewController:(SecondVC *)secondVC passInfo:(id)info{
    self.label.text = info;
}


@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值