Elegant way to share and alter an array between view controllers
I have two view controllers: LocationsViewController
, and SettingsViewController
. LocationsViewController
confo开发者_StackOverflow社区rms to the SettingsViewControllerDelegate
protocol. That protocol contains only 1 method:
// SettingsViewControllerDelegate.h
- (void)settingsViewControllerDidFinish:(SettingsViewController *)controller;
When my LocationsViewController
receives that delegate messages, it dismisses the SettingsViewController
that was presented modally.
I think this is good code design so far. The problem is the sharing of data between these view controllers. Both view controllers present the same data: an array of about 10 objects (locations). Only the SettingsViewController
allows altering of that array.
Right now I have 'solved' this in an inelegant way: both view controllers have a reference to my app delegate, and my app delegate has a locations
property. SettingsViewController
alters that array directly. For example:
// SettingsViewController.m
[appDelegate.locations addObject:newLocation];
It works, but I'm not happy with it. I understand it's a bad thing to just let your view controllers keep a reference to the app delegate. Any suggestions?
you might want to use an observer monitor the changes in the array i think. I could type something up but there are great answers in StackOverFlow already.
Key Value Observing with an NSArray
For situations like this, I use a singleton Settings
object. This is just an NSObject
that has methods for the settings in my application. I get an instance by calling +[Settings settings]
. Some settings are just a wrapper around NSUserDefaults
, and in that case I just define static methods.
Singletons are not exactly considered best practice either, but they're used all over the place in the SDK (plus, passing around an instance of settings to everybody gets annoying fast).
精彩评论