1

I have two view controllers: LocationsViewController, and SettingsViewController. LocationsViewController conforms 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?

Rits
  • 5,105
  • 4
  • 42
  • 53
  • In this case, you should definitely use a singleton. For 2016, be careful that you are using the *latest* correct idiom for singleton use in Swift. iOS features singletons from top to bottom (your app delegate is a singleton, your accelerator is a singleton, almost everything on a phone is a singleton), so you can't make anything but the most trivial iOS app without using singletons.BUT if you are a learner, do not OVERUSE singletons. They're critical but treat with care. – Fattie May 22 '16 at 13:11

2 Answers2

3

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

Community
  • 1
  • 1
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
1

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).

Brian
  • 15,599
  • 4
  • 46
  • 63
  • I guess it depends who you ask - some people knock singletons for being thinly-veiled global variables, and for making unit testing difficult, etc. – Brian Nov 10 '10 at 02:52