0
votes

suppose I got a singleton class MySingleton as coded below.

Now is a singleton class just like any other class. I can have instance variables that are nonatomic and retain?

I can have: @property (nonatomic, retain) NSString* instanceVar in the .h file

and @synthesize instanceVar in the .m file?

static MySingleton* _sharedMySingleton = nil;

+(MySingleton*)sharedMySingleton
{
    @synchronized([MySingleton class])
    {
        if (!_sharedMySingleton)
            [[self alloc] init];

        return _sharedMySingleton;
    }

    return nil;
}

+(id)alloc
{
    @synchronized([MySingleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }

    return nil;
}
4
Want to note that ARC will break existing Singleton implementations. They recommend using ARC to implement similar from now on. - Daryl Teo
You should use dispatch_once instead @synchronized, it's 20x faster. - Jano
If you're going to be multithreading then you want your singleton properties to be atomic to avoid race conditions (as well as wrapping the critical sections of your code with @synchronized directives). - jbat100

4 Answers

1
votes

You bet. To the rest of your application, your singleton looks and works just like any other class. The only difference is that when your application tries to create a new singleton it always receives back the same object. But the singleton can have instance methods and instance variables just like any other class.

1
votes

Yes, the instance of a singleton class behaves the same as a standard class, there is just one instance.

The pattern you have is overly complicated, there is no need for +(id)alloc Here is a simplier pattern:

@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;

+(MySingleton*)sharedMySingleton
{
    @synchronized([MySingleton class])
    {
        if (!_sharedMySingleton)
            _sharedSingleton = [[MySingleton alloc] init];
    }

    return _sharedMySingleton;
}
0
votes

Not familiar with the annotations you mentioned because I'm a C++ developer, but a singleton can certainly have instance data. That's one of its values.

0
votes

Yes you can have instance variables, a singleton is simply a regular class, where there is only one instance at any given time.