views:

92

answers:

3

What would be equivalent objective c for this:

template<class T>
class Singleton 
{ 
public: 
    static T * instance() 
    { 
        static T t; 
        return &t; 
    }
private: 
    Singleton(); 
    ~Singleton(); 
};

While calling:

friend class Singletone<MyManagerClass>;

+2  A: 

Objective C singleton examples

Wade Williams
Above C++ code is generic for creating Singleton object for any class. Which is not in your case. I am looking for Objective c class which can return singleton object for a given class. thanks
iPhoneDev
A: 

Oh thats Pretty easy!

@interface YourClass : NSObject {}
+ (YourClass *)singleton;
@end

static YourClass *singletonVar = nil;
@implementation YourClass
+ (YourClass *)singleton
{
  if( ! singletonVar ) {
    singletonVar = [[self alloc] init];
  }
  return singletonVar;
}
@end

Now you can call [[YourClass singleton] doSomething] anywhere! :D Just like you do [[NSUserDefaults standUserDefaults] valueForKey:@"Burp"] and such, do note that this ads overhead to your app, so when you use the singleton more than once in a scope consider storing it in a pointer for performance.

Antwan van Houdt
Above C++ code is generic for creating Singleton object for any class. Which is not in your case. I am looking for Objective c class which can return singleton object for a given class. thanks
iPhoneDev
It's not thread-safe but it will work fine otherwise.
dreamlax
+3  A: 
dreamlax
Thanks, so what should I write in objective c to acheive this.. please explore a bit
iPhoneDev