0

I have a custom ViewController class and many instances of it, and I want them all to be able to message the same Model (another custom class, only one instance). Passing pointers to the Model along to new instances of the ViewController seems impractical, especially since the model is lazily instantiated. What is the cleanest, most idiomatic, ARC way to do this?

mgold
  • 6,189
  • 4
  • 39
  • 41

1 Answers1

3

Usually a singleton in ObjC will have a class method that serves as an accessor for the single instance. The convention is for this to be called either defaultX or sharedX. If your model class is indeed a singleton, you should already have such a method. Since class names are globally available, all you have to do to access the instance anywhere in your program is [MyModelClass sharedModel].

jlehr
  • 15,557
  • 5
  • 43
  • 45
jscs
  • 63,694
  • 13
  • 151
  • 195
  • I haven't committed to the singleton design yet (sorry if that was unclear), so (1) is that a good idea given the needs I've outlined, (2) is [this way](http://cocoasamurai.blogspot.com/2011/04/singletons-your-doing-them-wrong.html) the right way to program it, in particular using ARC? – mgold Dec 25 '11 at 04:51
  • 1) Sounds like it -- if arbitrary view controllers need to access the same instance of the model, then it's almost _required_ to be a singleton. 2) Oh, boy, this is one of those areas that gets as close to Holy War as we ever get in Cocoa. See [What does your singleton look like?](http://stackoverflow.com/q/145154/), [Peter Hosey's blog](http://boredzo.org/blog/archives/2009-06-17/doing-it-wrong), and of course [Apple's docs](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32). – jscs Dec 25 '11 at 05:01
  • That said, the Cocoa Samurai post is a fine `sharedX` implementation, but there's usually more to do to have a fully-functional singleton. – jscs Dec 25 '11 at 05:02