views:

94

answers:

3

The first approach that comes to my mind is to put the singleton object in the appDelegate object as property. In this way you can access it from anywhere using

#import "myAppDelegate.h"
// ...
[[(myAppDelegate *)[UIApplication sharedApplication] delegate] SingletonObj]

The downside is you have to explicitly cast and import the header of your delegate to tell the class you're working with that SingletonObj is actually a property of the delegate. And I think this makes the code smell a little.

The second approach is to create a legit singleton class. This, however, require more work. And I personally think that one Singleton class, is more than enough.

I'm not a programmer so I would greatly appreciate corrections on my reasoning, and opinions on the subject.

+5  A: 

Singletons are most often handled in a class via a method like +sharedInstance.

Here is a good write-up.

bbum
Thanks, I also found this: In my experience, when you find that you’re embedding a lot of shared resources into your application delegate simply because it’s a convenient place to access them, that’s a good place to start thinking about singletons.
gurghet
I think I will go with the AppDelegate way, since I just have one single resource to be shared.
gurghet
A: 

Best practice is to only ever put UIApplicationDelegate-related things in your AppDelegate class. Evarr.

Decide if you really need a singleton. If you do, just make a legit singleton class. It will be easier in the long run; did you notice how long it took to type that monster of a line, where you tried to get the singleton object out of the AppDelegate? Agh.

(Also, just a little bit of idiom: classes start with a capital letter, and methods start with a lowercase letter; hence, you problem meant [[(MyAppDelegate *)[UIApplication sharedApplication] delegate] singletonObj].)

Jonathan Sterling
Except the "true" singleton is an anti-pattern. You can write `+[MyFoo sharedFoo]` or `+[MyAppDelegate sharedFoo]` to save typing, and I usually do to make my life easier.
tc.
Bullshit. The Singleton actually can be pretty useful. If you really think the Singleton should NEVvAARRRRR be used, then you'll need to stay as far away as possible from the Cocoa framework. Because it's full of singletons.
Jonathan Sterling
+1  A: 

I found a xcode template for easy singleton generation on the net.

vikingosegundo