代理传值(回调传值)

代理传值(回调传值)

1.代理又叫委托,是一种设计模式,代理是对象与对象之间的通信交互,代理解除了对象之间的耦合性。
2.改变或传递控制链。允许一个类在某些特定时间通知到其他类
3.代理的属性常用assign的原因是:防止循环引用,导致对象无法正确释放
代理是一种回调机制,是一对一得关系,通知是一对多,代理效率比通知高。

代理传值使用如下

一、在输入值的类的.h文件中声明一个到代理,并声明一个代理方法;
#import <UIKit/UIKit.h>
//声明一个AViewControllerDelegate 协议
@protocol AViewControllerDelegate <NSObject>
//@optional 为可选方法,如果不写则默认为必写方法
@optional
//声明代理方法
-(void)transValue:(NSString *)string;
@end
@interface AViewController : UIViewController
//找一个代理,并将其声明为属性
@property(nonatomic,assign)id<AViewControllerDelegate>delegate;

@end

二、在需要传值的页面的类的.m文件实现切换到输入值的页面,并实现传值方法
#import "ViewController.h"
//导入输入值的页面
#import "AViewController.h"
//遵守协议
@interface ViewController ()<AViewControllerDelegate>

//实现点击按钮切换页面
- (IBAction)push:(id)sender {
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    AViewController *aViewController = [storyboard instantiateViewControllerWithIdentifier:@"AViewController"];
    aViewController.delegata = self;
    [self presentViewController:aViewController animated:YES completion:^{
    }];
}
//实现传值方法
-(void)transValue:(NSString *)string{
    self.lable.text = string;
}

@end

三、在输入值的页面的.m文件实现点击按钮回到原页面,并传值
//实现点击按钮回原页面,并传值的方法
- (IBAction)pop:(id)sender {
//判断delegate是否存在,以及是否遵守协议
    if (self.delegata && [self.delegata conformsToProtocol:@protocol(AViewControllerDelegate)]) {
        [self.delegata transValue:self.textField.text];
    }
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值