Simple KVO example

前端 未结 3 2046
陌清茗
陌清茗 2021-02-05 02:01

I am trying to do simple KVO example, but I am having problems.

This is my *.m file:

#import \"KVO_ViewController.h\"

@interface KVO_ViewController (         


        
3条回答
  •  独厮守ぢ
    2021-02-05 02:24

    @interface TraineeLocationCell : UIView
    @property (strong, nonatomic) NSString *traineeAddress;
    @end
    
    @implementation
    
    // in textview delgate method  i am setting traineeAddress string value
    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        if (textView.text.length >0)
        [self setValue:textView.text forKey:@"traineeAddress"];
    
    }
    
    @end
    

    and in other class where i am using this class

     TraineeLocationCell *locationView;//create object here
     [locationView addObserver:self forKeyPath:@"traineeAddress" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];//observing the key in this class
    

    //this is the delegate method which take care of value is changed or not

    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
       if([keyPath isEqualToString:@"traineeAddress"]){
            if (!settingsValues.address)
                settingsValues.address = [[NSMutableArray alloc]initWithObjects:[change valueForKey:@"new"], nil];
    
            else
                [settingsValues.address replaceObjectAtIndex:0 withObject:[change valueForKey:@"new"]];
        }
    }
    

提交回复
热议问题