您的位置:首页 > 其它

代理传值(回调传值)

2016-03-23 17:56 453 查看

代理传值(回调传值)

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: