0

How can I make the reachability work as a singleton? Here is what I want to do ...

I have an application. When it launches I want to have a singleton and work with the reachability in order to hold the network status. Then I want from other controllers to access the singleton and check the network status. For example I want every time user clicks on one tab and the screen is shown to check the internet status and enable or disable a button.

I know the question is very generic but I am so confused. I am currently using reachability 2.2

Any tips or ideas or even guides will be appreciated.

And a final question.... how 'moral' is the singleton usage? And is it the best practice to be more close to MVC model?

Thanks again

auslander
  • 186
  • 3
  • 16

1 Answers1

4

Singletons are fine. Reachability can be a very sensible singleton. You should be aware of the doc "Creating a Singleton Instance" in Apple's Cocoa Fundamentals Guide, but read the text carefully. The code they present is seldom what you need and can cause more problems then it solves. It is only appropriate in cases where it is wrong for there to be multiple copies of the object (wrong because the object manages a unique resource for instance). In those cases, I tend to prefer asserting in -init rather than overloading allocWithZone: because I'd rather force the developer to make the correct call (+sharedInstance) rather than quietly fix it for them, and have them think they've created two instances when there is actually one (at least in cases where the singleton is mutable or holds state).

There is an excellent discussion of good singleton patterns in this question. I favor @Robbie Hanson's answer in my own code because it is cheaply thread-safe.

Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • What do you think about this [article](http://www.duckrowing.com/2010/05/21/using-the-singleton-pattern-in-objective-c/) on singletons? @Rob-Napier – auslander Mar 12 '11 at 07:17
  • 1
    I don't like @synchronize in +sharedInstance because it's expensive. I prefer using +initialize, because then you get thread-safety for free. I generally do not like overloading +allocWithZone, -release, etc., as I describe above. I believe it often masks programming errors, and is better to assert if someone tries to make multiple copies where this is illegal (seldom), and the rest of the time you should allow multiple copies of "singletons" (see NSNotificationCenter for a good example; this is the normal case). Look for "Singletons" here: http://robnapier.net/blog/learning-cocoa-2-467 – Rob Napier Mar 12 '11 at 18:51