1

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.

gurghet
  • 7,591
  • 4
  • 36
  • 63
  • 1
    You asked an intelligent question using words like "singleton", "appDelegate", "cast" and "smell". Sorry to do this to you, but there's no turning back. Just give in to the dark side because you ARE one of us... ;) – NotMe Sep 28 '10 at 18:31
  • LOL, here in Italy you're not a programmer until you know Linux – gurghet Sep 28 '10 at 18:39

3 Answers3

5

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

Here is a good write-up.

bbum
  • 162,346
  • 23
  • 271
  • 359
  • 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 Sep 28 '10 at 18:26
  • I think I will go with the AppDelegate way, since I just have one single resource to be shared. – gurghet Sep 28 '10 at 18:28
1

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

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
0

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
  • 18,320
  • 12
  • 67
  • 79
  • 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. Sep 28 '10 at 20:50
  • 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 Sep 29 '10 at 06:47