nitinsh99 nitinsh99 - 2 months ago 7
Objective-C Question

Delegating the even callback in objective-C

I am trying to wrap my head around how does the an event callback delegation works. So far I have written following code which btw works just fine:

Bridge.h

@protocol BridgeDelegate <NSObject>

- (void) bridgeLock;

@end

@interface Bridge : NSObject
+(instancetype) sharedInstance;
@property (weak, nonatomic) id<BridgeDelegate> bridgeDelegate;
- (void) wipe;


@end


Bridge.m

@implementation Bridge

+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}

-(instancetype) initUniqueInstance {
return [super init];
}

- (void) wipe
{
NSLog(@"lock in bridge called");

if(self.bridgeDelegate)
{
[self.bridgeDelegate bridgeLock];
}
}

@end


Plugin.h

@interface Plugin : NSObject<BridgeDelegate>

@property (strong, nonatomic) Bridge *bridge;
- (void) pluginInitialize;


@end


Plugin.m

@implementation Plugin


- (void) pluginInitialize
{
self.bridge = [Bridge sharedInstance];
self.bridge.bridgeDelegate = self;
}

- (void)bridgeLock
{
NSLog(@"lock in plugin called");


}

@end


When I call the following code in applicationDidBecomeActive

Bridge* bridge = [Bridge sharedInstance];
Plugin* plugin = [[Plugin alloc] init];
[plugin pluginInitialize];
[bridge wipe];


I get the following expected output:

lock in bridge called
lock in plugin called


Now my questions:


  1. How exactly is the delegate work? In the sense, Plugin is only implementing the function
    bridgewipe()
    , right? Why and how bridgeLock is being called at first place?

  2. Does this have anything to the fact that Bridge is a singleton. Had I made Bridge a non singleton class, will the end result be same.


Answer

1.How exactly is the delegate work? In the sense, Plugin is only implementing the function bridgewipe(), right? Why and how bridgeLock is being called at first place?

In the above pasted code "Plugin.m" is implementing - (void)bridgeLock

  1. Does this have anything to the fact that Bridge is a singleton. Had I made Bridge a non singleton class, will the end result be same.

No