三种传值(Block、代理协议、通知)

block

1   发送者定义block类型,
2   发送者创建block属性,
3   发送者将数据封装进block中,
4   接受者那里创建发送者对象,发送者调用带数据的block方法并实现处理数据的代码

//1 定义block
//returnType:返回类型,没有为void
//^<#name#>:Block名字
//arguments:参数
typedef <#returnType#>(^<#BlockName#>)(arguments);

//2 创建block属性
//copy修饰block类型
@property(nonatomic, copy)BlockName blockName ;

//3传入数据
_blockName(数据)

//4 接受者类里
(id)sender.blockName(数据){
    ... ...
}

代理协议

1   发送者创建代理协议,协议中约定方法,以及方法的参数和返回值
2   发送者创建代理属性
3   发送者通过代理调用协议方法,并传入数据
4   接受者签订协议,并设置发送者代理为自己,实现协议方法

//1 创建协议
@protocol <#protocol name#> <NSObject>

<#methods#>

@end
//2 创建代理
@property (nonatomic, weak)id<protocol name delegete;

//3 代理调用方法,传入数据
    if (_delegete) {
        [_delegete 协议方法];
    }
//4 接受者签订协议,创建发送者对象,设置发送者对象代理为自己,并实现协议方法
(id)sender.delegete = self;
-()协议方法{
    //处理数据
}

通知

//1 发送者发出通知,放入数据,若是在vc里,可在viewDidLoad时发出
//2 接受者接受通知,拿到数据,实现方法

//1发出通知
//[NSNotificationCenter defaultCenter]调用
//aName:通知的名字
//aUserInfo:将数据以字典形式封装
//object:可为nil
- (void)postNotificationName:(NSString *)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;

//收到通知
//[NSNotificationCenter defaultCenter]调用
//observer:接受通知的对象,数据接受者
//aName:通知的名字
//aSelector收到通知之后的动作
//object:nil
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;

//参数只能是(NSNotification *)
//notification.userInfo里面有数据
- (void)aSelector(NSNotification *)notification {

}
移除通知(必须移除),再覆写dealloc时
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值