Reputation: 1361
I have had about 6 hours trying to work out custom application delegates. even following tutorials i end up with errors!
I need a simple way of allowing one object to talk to another.
I have a root view. then another view which then pushes onto the stack with a list of options. then another view showing the relevant options based on the previous selection.
So basically 3 views, and i need view 3 to pass data back to view 1 when i popBackToRootViewController.... This is becoming a huge headache, for something that in theory should be so simple. I have previously just thrown data into nsuserdefaults but using protocols in the way apple suggest to do it.
Please can someone help me understand :)
Upvotes: 0
Views: 121
Reputation: 5766
There a different ways to solve that problem. First of all, you could pass the first View over and over to the View you are making changes on and then call a method of view 1. I won't recommend that.
Another, much easier way is to use Notifications. Just register your first View in the notification center [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingChanged) name:@"aStringWichIsUniqeForCallingSomethingChanged" object:nil];
. You have to provide and implement a callback method (somethingChanged in my case). In your subwiew where the things happen, you have to post a notification by doing [[NSNotificationCenter defaultCenter] postNotificationName:@"aStringWichIsUniqeForCallingSomethingChanged" object:nil];
. And don't forget to remove the view from the notificationcenter if they are not needed anymore!
[[NSNotificationCenter defaultCenter] removeObserver:self];
A third possibility is to use a singelton (like the app delegate) which contains all views that should communicate. Simple make all views as ivars & properties for them in this singleton and implement in each of them methods which should be called if something changes. Then call [[singelton sharedInstance] view1] somethingChanged]
.
If i say View, i mean viewController, but i'm to lazy to write that. ;) Hope, that helps!
Upvotes: 1
Reputation: 8990
Protocols and delegation formalize a concept which works even if you don't follow the formal rules: It's about declaring a way for objects to talk to each other about the same thing, especially in those cases where you either don't have or don't want control about one of the objects, or in cases where things get complex and you want everything nice and tidy so it's easier to reuse the code.
In those cases however where a rather small, well known set of information is to be passed back and forth between two (or more) well known objects which are unlikely to be reused, informality is quite ok.
This means you could:
As I mentioned before, this makes sense for glue code. You shouldn't be doing it this way though, if:
Upvotes: 0