1

I have a question regarding the safe way of implementing a singleton class in Objective-C. My background is mostly in web-development (PHP) but I know that in Obj-C things are quite different. For instance I have this custom class MyClass that I want to be singleton:

static MyClass *sharedInstance = nil;

@interface MyClass:NSObject
    NSMutableArray *someArray;
@end

@implementation MyClass:NSObject

-(id)init
{
    if(sharedInstance) {
        self = sharedInstance;
    } else if((self=[super init])) {
        sharedInstance = self;
        someArray = [[NSMutableArray alloc]initWithCapacity:10];
    }

    return self;
}

+(MyClass *)sharedObject
{
    if(!sharedInstance) {
        sharedInstance = [[MyClass alloc]init];
    }

    return sharedInstance;
}

@end
  1. It's ok this implementation?
  2. Since in Obj-C I can't make the constructor private (as far as I know, maybe I'm wrong), it's ok this way of creating the init method?
Bogdan
  • 843
  • 1
  • 9
  • 26

2 Answers2

2

As gnasher729 states, you need to use dispatch_once_t for the sake of thread safety.

+(MyClass *)sharedObject
{
    static MyClass *sharedObject = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        sharedObject = [[self alloc] init];
        sharedObject.someArray [[NSMutableArray alloc] initWithCapacity:10];
    });
    return sharedObject;
}
Community
  • 1
  • 1
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • If I want to use `someArray` in other method for this class, how would I use it ? – NSPratik Jul 09 '15 at 08:58
  • just add below line of code into your singleton class. - (id)copyWithZone:(NSZone *)zone { retun [self sharedObject]; } – Kiran K Apr 25 '16 at 12:29
1

See this link Create singleton using GCD's dispatch_once in Objective C for the recommend approach to creating a singleton.

Using gcd, the code becomes thread-safe. Most people now consider the case that someone calls [[Singleton alloc] init] a bug that you wouldn't write code for, so the init method should just initialise the object.

Community
  • 1
  • 1
gnasher729
  • 51,477
  • 5
  • 75
  • 98