Can the AVAudioPlayer delegate be set to a class member audioPlayerDidFinishPlaying?
I want to use a class method to play a sound file, but can’t figure out how to set setDelegate: to the audioPlayerDidFinishPlaying class method.
I have a small class called ‘common’ with just static members.
Please see ‘<<<<‘ flag below…
@class common;
@interface common : NSObject <AVAudioPlayerDelegate> {
}
+(void) play_AV_sound_file: (NSString *) sound_file_m4a;
+(void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) flag
@end
@implementation common
AVAudioPlayer* audioPlayer;
// Starts playing sound_file_m4a in the background.
+(void) play_AV_sound_file: (NSString *) sound_file_m4a
{
printf("\n play_AV_sound_file '%s' ", [sound_file_m4a UTF8String] );
NSString *soundPath = [[NSBundle mainBundle] pathForResource:sound_file_m4a ofType:@"m4a"];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: soundPath] error:&error ];
[audioPlayer setDelegate:audioPlayerDidFinishPlaying]; //<<<<<<<<<< causes error
>>> what should setDelegate: be set to? <<<
[audioPlayer prepareToPlay];
[audioPlayer play];
}
+(void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) flag
{
printf("\n audioPlayerDidFinishPlaying");
[audioPlayer release];
audioPlayer=nil;
[audioPlayer setDelegate:nil];
}
@end
That’s not how delegates work.
You assign a class instance to be a delegate for another instance. Now in your case, this isn’t easy, as a class method isn’t part of an instance (it’s static). As such, you’ll need to make a Singleton, in order to produce one global instance for your class (which is equivalent to providing class methods).
To do so, make
commona singleton by providing this as your only class method:From then in, in your example , you’d use.
In doing so, you need to make sure your
commonclass (which ideally should have a capitalC), has an instance method, that follows theAVAudioPlayDelegateprotocol (which by the looks of it, it does for class methods). You’d need to changeto
In my opinion, having a singleton as a delegate for something isn’t great design. In answer to your original question though, no, you can’t assign class methods as individual delegates, you can only set instances of whole classes. I’d strongly suggest you read up on how delegation works:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW18