Frage

I have an app that requires that a menu changes in view controller 1 when a button in view controller 2 is pressed. What is the best way to achieve this?

I've heard a lot of talk about NSNotification but I thought that was for displaying alerts?

War es hilfreich?

Lösung

The "right" way to do this is to write the new state into the app's data model. When another view controller becomes active, it should update its view according to what the model says. That way, the information will be available to other view controllers even if they don't exist when the user makes the change.

Notifications are a great way to convey information to other objects without having to know about them specifically, but a notification is only effective if the objects that care about it exist at the time that it's sent.

Andere Tipps

You're thinking about this in the wrong way. One view controller shouldn't care about what happens in another view controller.

If a button being tapped results in changes to the contents of a menu, it sounds like you're changing the data. The button press should tell the model layer that the available options have changed, and the other view controller should load the available options into the menu from the model layer.

I've heard a lot of talk about NSNotification but I thought that was for displaying alerts?

No, it is for distributing information about events to the rest of your application in a way that doesn't couple those parts together. It's not about interacting with the user.

NSNotification is one way to do it and no, it has nothing to do with alerts.

It works like this: a "producer" can post (send) a notification. Other objects can subscribe to notifications and react to the notification. It's an excellent way to decouple objects (the goal is often to make each object know as few information about the other as possible).

Search for NSNotification tutorial, there are quite a few. You should really get familiar with them, they are used a lot on iOS and Mac OS X development as they are very, very handy.

If you're not presenting both viewcontrollers at same time and you transition from viewcontroller1 to viewcontroller2 you could use segues to pass information from vc1 to vc2. I think notifications are great but i think isn't necessary.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top