iOS原生控件资料整理

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

2016-09-06  本文已影响42人  郑州程序员王一

使用场景

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的简单使用

//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];
     }

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

上一篇 下一篇

猜你喜欢

热点阅读