I create new tabbed view project in xcode, in appdelegate I created a protocol
.h file
@protocol myProtocol <NSObject>
-(void)myProtocolMethodOne;
@end
.
.
.
@property (weak) id<myProtocol> mypDelegate;
.m file
@synthesize mypDelegate;
.
.
.
//Inside didFinishLaunchingWithOptions
[mypDelegate myProtocolMethodOne];
In firstViewController & secondViewController (both are displayed as two different tab) I did this in both
AppDelegate *ad = (AppDelegate*)[[UIApplication sharedApplication]delegate];
[ad setMypDelegate:self];
.
.
.
-(void)myProtocolMethodOne
{
NSLog(@"1st VC");
[[self tabBarItem]setBadgeValue:@"ok"];
}
The code is working perfectly but only secondViewController is responding.
I am looking for a broadcasting and listener kind of mechanism using delegates not notifications.
I searched a lot but did find any solutions except this but code is advance for me to understand, so I am taking a step by step approach to understand this by starting form a simple project. Please help me regarding this. How both viewcontrollers can respond to delegate at same time, what should I do?
In your case is enough to hold an array with all delegates, by holding an array of delegates, possibly as a private property, and allowing to add/remove delegates:
I leave to you the removeDelegate method, it’s very simple to implement.
How to call the delegates methods
It’s enough to call the selector on every object:
If you need to take return values it’s better to do it this way:
How to add the delegates
In every controller (up to N times) you should be able to add it:
Additional problem: You may want to have weak delegates, but a NSArray holds strong references. Here you can find a nice solution for this:
NSArray of weak references (__unsafe_unretained) to objects under ARC
It basically says to use NSValue to store weak reference using the valueWithNonretainedObject method.