1

How can I make a viewcontroller singleton, to then use this code:

FacebookManager *manager = [FacebookManager sharedManager];
[manager openSessionWithAllowLoginUI:NO]

??

Alessandro
  • 4,000
  • 12
  • 63
  • 131
  • Singletons are bad, didn't you get the memo? – Etienne de Martel Nov 19 '12 at 18:59
  • It's mostly off-topic, but the singleton is essentially an anti-pattern (i.e. it's not useful and even _harmful_ to use it). See [this question](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) for more details. – Etienne de Martel Nov 19 '12 at 20:02

1 Answers1

2

That's not necessarily a singleton. A singleton can only have one instance at any given time. Shared instances are similar, but don't prevent additional instances from being created.

You can implement a shared instance with a static variable and a class method like this:

+ (FacebookManager *)sharedManager
{
    static FacebookManager *shaderManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shaderManager = [[FacebookManager alloc] init];
    });
    return shaderManager;
}

Don't forget to declare the class method in your header.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • My code is correct, I used that in a project myself. Posting "it's not working" is NOT useful. Elaborate! – DrummerB Nov 19 '12 at 19:14
  • sorry, it says that the sharedManager is not declared nowhere: "No known class method for selector sharedManager" – Alessandro Nov 19 '12 at 19:27
  • Did you declare the method in the header? – DrummerB Nov 19 '12 at 19:29
  • what do I need to add in the header? – Alessandro Nov 19 '12 at 19:44
  • 3
    The declaration of the method obviously... Why are you trying to write a complete app with Facebook support without learning the basics of the language first? I'm not going to write your app for you, sorry. Read [**The Objective-C Programming Language**](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html), especially the **Defining a Class** part. Then, if you still have questions, come back and ask. – DrummerB Nov 19 '12 at 19:53