Strong Like Bull
Strong Like Bull

Reputation: 11297

Can my singleton be improved?

I am somewhat new to iOS 5 singletons and am using a singleton as documented here:

iOS 5 Singletons

Something like this:

MyManager.h

#import <Foundation/Foundation.h>
@interface MyManager : NSObject

//Data for section 1
@property(nonatomic,copy) NSString * section1a;
@property(nonatomic, assign) NSUInteger section1b;


//Data for section 2
@property(nonatomic,copy) NSString * section2a;
@property(nonatomic, assign) NSUInteger section2b;

+ (id)sharedInstance;
@end

MyManager.m

@implementation MyManager
@synthesize section1a, section1b, section2a; , section2b;

+ (id)sharedInstance
{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init]; // or some other init method
    });
    return _sharedObject;
}
@end

So I use it as follows:

MyManager * myManager = [MyManager sharedInstance];
myManager.data = self.data

Is this how you generally use the singleton? Am I missing anything? Sorry for the basic questions I just want to make sure I am doing it right.

Thanks

Upvotes: 2

Views: 192

Answers (4)

Καrτhικ
Καrτhικ

Reputation: 3915

Refer to this: Singleton in iOS 5? You should override allowWithZone to prevent rogue code from creating a new instance.

Upvotes: 0

Andreas Ley
Andreas Ley

Reputation: 9335

You're doing it right. This is (currently :) the way to go and works fine with ARC enabled, multiple threads etc.

It isn't strictly a singleton, as you can alloc more instances of the class, but I don't think that's relevant in your case.

Upvotes: 1

Nosrettap
Nosrettap

Reputation: 11320

I usually make my singleton as such (suppose we are making a singleton for Manager):

static (Manager *) instance;

+ (Manager *) getInstance
{
    if(!instance) instance = [[Manager alloc] init];
    return instance;
}

This is a very basic singleton (it doesn't take into account multithreading or other advanced features) but this is the basic format.

Upvotes: 0

iSofTom
iSofTom

Reputation: 1718

This is not a singleton because you can create multiple instances of this class with alloc/init methods. A right answer is here

Upvotes: 1

Related Questions