Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe a key path like "object.attribute"

greetings , I'm a cocoa beginner and this is my first post:P

I'm trying to make a very simple rhythm game but get stuck , here's what I got:

/**** TouchView.h/m ****/
@property AVAudioPlayer *audioPlayer;

[self addObserver:self 
       forKeyPath:@"audioPlayer.currentTime" 
          options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
          context:NULL];

//audioPlayer.currentTime's type is NSTimeinterval (double)

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change (NSDictionary *)change context:(void *)context
{
   NSLog(@"action triggered!")
}

which doesn't work (I have initialized audioPlayer properly,it can play sound but just can't be caught when its currentTime value changes)

I test these code with another property "double testNumber" , set it as the argument of "keyPath" , increase it by one when I touch the screen , then that works well. But what should I do to make audioPlayer.currentTime can be observed , I just want to get notified when this value changed , any other advice will also be appreciated. I'm counting on you , please help me ,thanks :)

like image 421
mario.hsu Avatar asked Dec 06 '25 06:12

mario.hsu


1 Answers

How about:

[audioPlayer addObserver:self
              forKeyPath:@"currentTime"
                 options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
                 context:NULL];

However if you really want to make your object KVC-compliant (which is what you're attempting to use), you need to follow Apple's guide on the subject:

In order for a class to be considered KVC compliant for a specific property, it must implement the methods required for valueForKey: and setValue:forKey: to work for that property.

like image 176
trojanfoe Avatar answered Dec 07 '25 21:12

trojanfoe