Last active
June 10, 2020 19:02
-
-
Save gilesvangruisen/68943423e25d51b2b3e2 to your computer and use it in GitHub Desktop.
Basic pub/sub with Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface Publisher : NSObject | |
- (void)subscribe:(void(^)(id object))subscriptionBlock; | |
- (void)publish:(id)object; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "Pubslisher.h" | |
@interface Subscriber : NSObject | |
@property (nonatomic, strong) Pubslisher *pubslisher; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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: 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
can you please explain how to use?