0

As Apple encourages the usage of blocks, and i wanted to do a series of animations, with sound output in between them which is basicly like a todolist, i wanted to implement this using blocks.

unfortunatly AVAudiosplayer doesnt appear to support onCompletion blocks, in the manner UIAnimation does.

So i thought it would be cool to add that support to the AVAudioplayer.

so what ive dont is this

header

#import <AVFoundation/AVFoundation.h>

@interface AVAudioPlayer (AVAudioPlayer_blockSupport)

typedef void(^AVPlaybackCompleteBlock)(void);

@property (nonatomic, copy) AVPlaybackCompleteBlock block;

-(id)initWithContentsOfURL:(NSURL*)pathURL error:(NSError**)error onCompletion:(AVPlaybackCompleteBlock) block;
-(void)setBlock:(AVPlaybackCompleteBlock)block;
-(AVPlaybackCompleteBlock)block;
-(void) executeBlock;

@end

and the m file

#import "AVAudioPlayer+blocks.h"

@implementation AVAudioPlayer (AVAudioPlayer_blockSupport)

-(id)initWithContentsOfURL:(NSURL *)pathURL error:(NSError **)error onCompletion:(AVPlaybackCompleteBlock )block {
    self = [[AVAudioPlayer alloc] initWithContentsOfURL:pathURL error:error];
    self.block = block;
    return self;
}

-(void)setBlock:(AVPlaybackCompleteBlock)block {
    self.block = block;
}
-(AVPlaybackCompleteBlock)block {
    return self.block;
}

-(void) executeBlock {
    if (self.block != NULL) {
        self.block();
    }
}

@end

after doing this, i thought i should be able to create a new audioplayer like this:

player = [[AVAudioPlayer alloc] initWithContentsOfURL:pathURL error:&error onCompletion:block];

this appears to be working.

now in the delegate will try to execute the block attached.

if (localPlayer.block) {
    [localPlayer executeBlock];
}

unfortunately when i try to run the code, it appears to be looping infinitely. I wanted to use synthesize instead, but thats not for category use...

If i dont implement that Method im stuck with '-[AVAudioPlayer setBlock:]: unrecognized selector sent to instance which makes sense, since there is no method with that name.

i found this Block references as instance vars in Objective-C so i thought i should be able to attach the additional property(my Block) to the AudioPlayer.

Community
  • 1
  • 1
Daniel Bo
  • 2,518
  • 1
  • 18
  • 29

1 Answers1

0

I figured it out, i needed to use

objc_setAssociatedObject(self, &defaultHashKey, blocked, OBJC_ASSOCIATION_COPY_NONATOMIC);

to store and access the property. maybe thats what jere meant with, i have tot ake care of the memory management myself.

-(void)setBlock:(AVPlaybackCompleteBlock)blocked {
    objc_setAssociatedObject(self, &defaultHashKey, blocked, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(AVPlaybackCompleteBlock)block {
    return objc_getAssociatedObject(self, &defaultHashKey) ;
}
Daniel Bo
  • 2,518
  • 1
  • 18
  • 29