1、代理传值。(逆向)
代理是一对一的关系,只能跟navigation的栈里相邻的控制器之间传值。
场景:a->b , b->a时 我们需要把b的数据传递到a中 。在这里我传递了一个UIview ,通常开发中如果数据较多可以考虑传递一个模型过去。
1> 在b的.h中定义一个protocol ,注意点:一定要遵循<NSObject> 注: 在.h和.m的interface中声明是有区别的。 .h中声明是共有属性,.m中声明是私有属性。
@protocol bContorllerDelegate <NSObject>
-(void)changeViewColor:(bContorller *) VC andView :(UIView *)view;
@end
2>在b的.h中声明一个 id类型并且遵循协议的 的 delegate属性。 这里需要注意的是我们用weak修饰,主要是为了避免 循环引用。
@property(nonatomic,weak)id<bContorllerDelegate> delegate;
3>在b的.m中在适当的时候调用代理。 先判断是否实现了该方法 ,再去调用。
if ([self.delegate respondsToSelector:@selector(changeViewColor: andView :)]) {
[self.delegate changeViewColor:self andView:self.myView];
}
4>在a的.m中遵循该协议。当然记得引入b的头文件。
@interface ViewController ()<bContorllerDelegate>
5>在能够获得b控制器的地方 设置代理对象。 (这里比较关键)
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.destinationViewController isKindOfClass:[TVcontorller class]]) {
TVcontorller * tvc =segue.destinationViewController;
tvc.delegate = self;
}
}
6>实现代理方法。
-(void)changeViewColor:(TVcontorller *)VC andView:(UIView *)view{
//将传递进来的view的背景色赋值给 a控制器view的backgroundcolor
self.myView.backgroundColor = view.backgroundColor;
}
2、block传值(逆向)
block 相对来说也是一对一的。使用起来比delegate简单点。
场景: a->b ,b->a时 把b的值传递给a。
1>在b的.h声明一个block类型的属性.
@property(nonatomic,copy)void(^fanhui)(NSString * str);
2>在适当的地方调用block。 注:一定要判断 防止崩溃。
if (self.fanhui) {
self.fanhui(self.mylable.text);
}
3>在适当的地方调用。 注: __weak __typeof(self) wekeSelf = self; 为了防止循环引用
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.destinationViewController isKindOfClass:[TVcontorller class]]) {
bContorller *bvc = segue.destinationViewController;
__weak __typeof(self) wekeSelf = self;
bvc.fanhui = ^(NSString * str){
wekeSelf.mylable.text = str;
};
}
}
3、单例传值
单例传值可包括 系统单例和自定义单例传值,这里的演示为自定义的。
逆向
1>创建一个单例。 包括一个传递的值类型的属性。
.h中
#import <Foundation/Foundation.h>
@interface testModel : NSObject
@property (nonatomic,copy)NSString * modelStr;
+(instancetype)shardModel;
@end
.m中
@implementation testModel
+(instancetype)shardModel{
static testModel * _shardModel;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_shardModel = [[testModel alloc]init];
});
return _shardModel;
}
@end
2>在a的.m中给单例属性赋值。
testModel * model = [testModel shardModel];
model.modelStr = @“123”;
3>选择在哪里去
有时间我再更新一下 单例未完。