Thursday, July 23, 2015

Creating an object with multiple delegates in iOS 8

Sometimes one delegate is just not enough and notifications are just not reliable or their timing is to unpredictable. Here comes the solution, multiple delegates! Bonus, this should be multithreading safe.

The multiple delegates still will not give you an order on which receiver gets the information first but if you want that, you aren't programming correctly.

First you need to make a delegate protocol;

@protocol AudioPlayerDelegate <NSObject>
@optional
- (void)AudioPlayer:(AudioPlayer *)audioEngine onStateChange:(StreamStatusType)state;

@end

in the interface, create the delegate calls;

//Delegates
- (void)addDelegate:(id<AudioPlayerDelegate>)aDelegate;
- (void)removeDelegate:(id<AudioPlayerDelegate>)aDelegate;

Also in the interface create a private delegate as a hashtable;

@private
  NSHashTable *delegates;

in the implementation, setup the delegates in the init;

  delegates = [NSHashTable weakObjectsHashTable];

and create the methods;

#pragma mark - Delegates

- (void)addDelegate:(id<AudioPlayerDelegate>)aDelegate {
    [delegates addObject:aDelegate];
}

- (void)removeDelegate:(id<AudioPlayerDelegate>)aDelegate {
    [delegates removeObject:aDelegate];
}

when you want to use them, here is the best and safest way to do so;

    __weak AudioPlayer *weakSelf = self;
    id<AudioPlayerDelegate> delegate = nil;
    for (delegate in [delegates copy]) {
        if (delegate && [delegate respondsToSelector:@selector(AudioPlayer:onStateChange:)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [delegate AudioPlayer:weakSelf onStateChange:weakSelf.streamStatusType];
            });
       }
    }

This might be overkill but it is always good to be thread safe. 

And that's it! 

1 comment: