3

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 :)

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
mario.hsu
  • 97
  • 5

1 Answers1

1

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.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Thanks for the info,though the trick doesn't work either XD. Maybe it's because when currentTime changes automatically, accessor methods(set/get/valueForkey/setValueForKey) do not even get called. I add setValueForKey:@"currentTime" in -(void)touchesBegin: , then when I touch the screen , observer's action is triggered, so I think this property is KVC compliant. Now my thought is to observe another value which is assigned to the value of currentTime , use a while loop tracking the currentTime's value until music finished , but wherever I put it,app will be blocked within it – mario.hsu Dec 05 '12 at 06:49
  • So I want to try something on NSThread , hoping that will help , otherwise I'll have to look into other sound engines like OpenAL or FMOD... which will lead a much harder life :( anyway , thanks again for your answer,I learned something through it – mario.hsu Dec 05 '12 at 06:54