Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

Objective-C: Singleton Pattern Usage

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;
}

Upvotes: 0

Views: 618

Answers (4)

zaph
zaph

Reputation: 112857

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;
}

Upvotes: 1

Oscar Gomez
Oscar Gomez

Reputation: 18488

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

Upvotes: 0

Carter
Carter

Reputation: 4758

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.

Upvotes: 1

Thom
Thom

Reputation: 15052

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.

Upvotes: 0

Related Questions