通知、Block、代理的简单使用

使用场景

1.回调方法 在日常的开发过程中,我们经常会遇到一些完成之后的处理问题,比如完成网路请求之后的回调,或者页面加载完成之后的回调等。这个时候我们一般使用的是Block或者Delegate。而在一对一传输回 调的时候明显Block的使用更加的简单高效,只需要在代码块中执行所需要的操作即可。在一对多的情况下,Delegate更加能够发挥出自己的优势。

2.跨层通信 有的时候我们需要实现在两个毫无关联的对象之间的通信,这个时候如果使用Block或者Delegate就势必会增加代码的耦合性,这样对于代码的结构来说是不健康的,因此这个时候使用Notification便是明智的选择。

3.UI响应事件 用户在于App的UI进行互动的时候,总会需要App进行交互响应,这个时候就毫无疑问的使用代理设计模式。而苹果官方给出的建议也是可以肯定的,在Cocoa Touch框架中我们也可以在几乎所有的UI交互控件的头文件里看到Delegate的成员变量,也正是印证了在UI响应事件上Delegate有着绝对的优势。

4.简单值得传递 当需要进行简单值得传递的时候,比如子控件传输给父控件所点击的IndexPath的时候,更加适合使用Block来传值。因为,如果只是为了传这一个简单的值而没有特别的业务处理而定义一个协议,然后实现协议,设置代理再写方法的话将十分麻烦,得不偿失,这个时候简单高效的Block就可以完美的替代Delegate完成任务了。

通知简单使用一:

  • 注册通知观察者
[[NSNotificationCenter defaultCenter] postNotificationName:@"downloadWebImage" object:image];
  • 接受通知观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setUpImageWithNotify:) name:@"downloadWebImage" object:nil];
  • 接收到通知之后,执行的方法.
-(void)setUpImageWithNotify:(NSNotification *)notify {
     // 1.取出通知内容
     UIImage *image = notify.object;
     // 2.显示图片
     self.imageView.image = image;
}
  • 移除通知观察者
-(void)dealloc{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

通知简单使用二:

  • 注册通知观察者
[[NSNotificationCenter defaultCenter]postNotificationName:@"orderJumpNotification" object:nil userInfo:@{@"key":@(indexPath.row)}];
  • 接受通知观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orderJumpNotification:) name:@"orderJumpNotification" object:nil];
  • 接收到通知之后,执行的方法.
-(void)orderJumpNotification:(NSNotification *)notify{
    NSDictionary *userInfo = notify.userInfo;
    self.numberNotification = userInfo[@"key"];
}
  • 移除通知观察者
-(void)dealloc{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Block的简单使用

  • 比如:有A界面、B界面,
  • 关系:A界面跳转B界面。
  • 场景:在B界面输入数值,A界面获取。
//B界面.h声明Block
typedef void(^textValue)(NSString *string);
@property(nonatomic,copy)textValue block;
//B界面.m跳转返回方法中执行block
-(void)clickBtn{
    if (self.block) {
        self.block(self.textField.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
//A界面.m跳转B界面的方法
-(void)clickBtn{
    TwoViewController *vc = [[TwoViewController alloc]init];
    
    __weak ViewController *wself = self;
    vc.block = ^(NSString *string){
        wself.label.text = string;
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

代理的简单使用

     //.h中声明代理方法和协议
     @class WYBaby;

     @protocol WYBabyDelegate <NSObject>
     -(void)babyCry:(WYBaby *)baby;
     @end

     @interface WYBaby : NSObject
     @property(nonatomic,weak)id <WYBabyDelegate>delegate;
     @end
     //.m代理对象判断下是否执行
     if ([self.delegate respondsToSelector:@selector(downLoadViewLoadBtnDidClick:)]) {
         [self.delegate downLoadViewLoadBtnDidClick:self];
     }

勤学如早春之苗,不见其增,日有所涨。
辍学如磨刀之石,不见其减,日有所损。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容