2013年3月26日 星期二

Key-Value Observing機制

//這是一個簡單又好用的機制
//對你要觀察的物件calendar加入觀察者self,再把你想要觀察的屬性calendar.selectedDate,就會在屬性值改變時呼叫下面的方法
- (void)viewDidLoad{

//對calendar做KVO
 [self.calendar addObserver:self forKeyPath:@"selectedDate" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

}

//加入一個下列的方法,一旦上面的觀察值有所改變,就會執行下面的方法
-(void) observeValueForKeyPath:(NSString *)keyPath
                                      ofObject:(id)object
                                        change:(NSDictionary *)change
                                       context:(void *)context
 {
      NSLog(@"observeValueForKeyPath is run");
   if([keyPath isEqual:@"selectedDate"]){
        //改變值存在change這個dictionary中,要用key= old或new去取值
        NSLog(@"old price is %@",[change objectForKey:@"old"]);
        NSLog(@"new price is %@",[change objectForKey:@"new"]);
       
    }
 }

沒有留言:

張貼留言