在iOS使用KVO时候的坑

来源:互联网 发布:看网络直播用什么软件好 编辑:程序博客网 时间:2024/05/29 10:43

看下面的代码 

 //设置眼睛

       UIButton *button= [[UIButtonalloc]initWithFrame: (CGRect){{self.width -self.height,0},{self.height,self.height}}];

        

        button.backgroundColor = [UIColorredColor];

        [button addTarget:selfaction:@selector(changePassWord)forControlEvents:UIControlEventTouchUpInside];

        

       self.eyeButton = button;

       self.eyeButton.hidden =YES;

       //注册监听者

        [self.eyeButtonaddObserver:selfforKeyPath:@"hidden"options:NSKeyValueObservingOptionNewcontext:nil];

        [selfaddSubview:button];




#pragma mark - 设置眼睛,如果设置的眼睛是显示状态那么就要进行textField的宽度减少

/**

 *  监听者的响应者事件

 *

 *  @param keyPath hidden

 *  @param object  button

 *  @param change  值如果进行改变

 *  @param context

 */

- (void)observeValueForKeyPath:(NSString *)keyPath

                      ofObject:(id)object

                        change:(NSDictionary *)change

                       context:(void *)context {

        if ([keyPath isEqualToString:@"hidden"] && object ==self.eyeButton ) {

        

        _textField.width =self.eyeButton.x -pixw(6);

        _placeHolderLabel.width =_textField.width  ;

    }

   else

        [superobserveValueForKeyPath:keyPath ofObject:object change:change context: context];

    

}

-(void)dealloc

{

    [self.eyeButtonremoveObserver:selfforKeyPath:@"hidden"];

}


潜在的问题有可能出现在dealloc中对KVO的注销上。KVO的一种缺陷(其实不能称为缺陷,应该称为特性)是,当对同一个keypath进行两次removeObserver时会导致程序crash,这种情况常常出现在父类有一个kvo,父类在dealloc中remove了一次,子类又remove了一次的情况下。不要以为这种情况很少出现!当你封装framework开源给别人用或者多人协作开发时是有可能出现的,而且这种crash很难发现。
0 0