Skip to content

Instantly share code, notes, and snippets.

@gilesvangruisen
Last active June 10, 2020 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilesvangruisen/68943423e25d51b2b3e2 to your computer and use it in GitHub Desktop.
Save gilesvangruisen/68943423e25d51b2b3e2 to your computer and use it in GitHub Desktop.
Basic pub/sub with Objective-C
@interface Publisher : NSObject
- (void)subscribe:(void(^)(id object))subscriptionBlock;
- (void)publish:(id)object;
@end
#import @"Pubslisher.h"
@interface Publisher ()
// Mutable array to hold subscription blocks
@property (nonatomic, strong) NSMutableArray *subscriptionBlocks;
@end
@implementation Publisher
- (id)init {
self = [super init];
if (self) {
self.subscriptionBlocks = [@[] mutableCopy];
}
return self;
}
- (void)subscribe:(void(^)(id object))subscriptionBlock {
[self.subscriptionBlocks addObject:subscriptionBlock];
}
- (void)publish:(id)object {
[self.subscriptionBlocks enumerateObjectsUsingBlock:^(void(^subscriptionBlock)(id object), NSUInteger index, BOOL *stop) {
subscriptionBlock(object);
}];
}
@end
#import "Pubslisher.h"
@interface Subscriber : NSObject
@property (nonatomic, strong) Pubslisher *pubslisher;
@end
#import "Subscriber.h"
@implementation Subscriber
- (void)setPublisher:(Publisher *)publisher {
_pubslisher = publisher;
// Subscribe to publisher
[_publisher subscribe: ^ (id object) {
// Called every time publish: is called upon _publisher
NSLog(@"%@", object);
}];
}
@end
@Gagan5278
Copy link

can you please explain how to use?

@GWBasic
Copy link

GWBasic commented Jun 10, 2020

@Gagan5278: Take a few minutes to read through the code. I'm not an Objective C expert and it looks very straightforward to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment