iOS开发中 代理,block,KVO 的使用

来源:互联网 发布:网络兼职是真是假 编辑:程序博客网 时间:2024/06/05 04:57
1.代理
IPView.h
@protocol TPViewDelegate <NSObject>
- (void)IPView:(UIView*)view finishEdit:(NSString *)text;
@end
@interface IPView : UIView <UITextFieldDelegate>
@property (nonatomic,assign)id<TPViewDelegate> delegate;
@end
IPView.m
- (void)pushMessage{
    [
_textView endEditing:YES];
   
if (str!= nil) {
        [
self.delegateIPView:self finishEdit:str];
    }
   
self.hidden= YES;
}
ViewController.m
- (void)IPView:(UIView*)view finishEdit:(NSString *)text{
   
self.label.text= text;
}


2.闭包
BLView.h
typedefvoid(^textBlock)(NSString *);
@interfaceBLView : UIView <UITextFieldDelegate>
@property (nonatomic,copy)textBlockmyTextBlock;
@end

BLView.m
- (void)pushMessage{
    [
_textView endEditing:YES];
   
if (self.str!= nil) {
       
self.myTextBlock(self.str);
    }
   
self.hidden= YES;
}

ViewController.m
    _BLView.myTextBlock= ^(NSString *str){
         self.label.text= str;
    };


3.KVO
BLView.h
#import <UIKit/UIKit.h>
@interface BLView : UIView <UITextFieldDelegate>
@property (nonatomic,copy)NSString*str;
@end

ViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
...
     
    /**
     * 
被观察者
     *
     * 
@param NSObject 观察者
     * 
@param KeyPath 被观察的属性路径
     * 
@param options 返回的值的类型
     {    NSKeyValueObservingOptionNew = 0x01, 
变化之后的值
          NSKeyValueObservingOptionOld = 0x02, 
变化之前的值
     }
     * 
@param context 一般写nil
     *

     */
    [_BLView addObserver:selfforKeyPath:@"str"options:NSKeyValueObservingOptionNewcontext:nil];
}
// 观察者的方法
/**
 * 
当观察者 监视的属性发生变化时候调用的方法
 *
 * 
@param keyPath 观察的属性
 * 
@param object  被观察的对象
 * 
@param change  属性的值
 * 
@param context nil
 */
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context{
   
self.label.text= change[@"new"];
}
0 0