0

I am trying to figure out the best implementation of a singleton this is the latest I got.

This is the .m file implementation, anything wrong with it:

#import "Foo.h"

static Foo *object = nil;

@implementation Foo

+ (Foo*)sharedObject {
   return [[Foo alloc] init];
}

- (id)init {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
       object = [super init];
    });

  return object;
}

@end

and to use it I can do:

[Foo sharedObject]

or

[[Foo alloc] init]

And both will return the same object.

Jaywant Khedkar
  • 5,941
  • 2
  • 44
  • 55
Ahmad Al-Attal
  • 435
  • 4
  • 13
  • What you are doing is a bad practice and it's a wrong way to do singletons. `alloc init` must always return an instance, not a lazy allocated singleton. See @isamankumara answer for right coding pattern. – Shebuka Sep 20 '17 at 10:56
  • Why are u saying it's a must, i think your (must) my friend is the exact the deference of a singleton. and this is the exact reason why i wrote this question. singleton is one and only one instance of this class, otherwise it's not a singleton – Ahmad Al-Attal Sep 20 '17 at 12:39

1 Answers1

0

According to the your Foo class. No any different when you call both two methods. But I think better if you can change your Foo singleton method as follows

+ (id) sharedObject {
    static Foo *sharedobj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedobj = [[self alloc] init];
    });
    return sharedobj;
}

- (id)init {
  if (self = [super init]) {
      someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
  }
  return self;
}

Lets assume you want to create new instance. But it will not create using alloc method because you are overriding init method.

  • my concern about your solution is that i am still able to create an instance if i called the init method, but with my code no matter if you called -init or +sharedObject it will still return the same object. and according to my understanding for the singleton design pattern, you shouldn't be able to create another instance of this class in anyway. – Ahmad Al-Attal Sep 20 '17 at 12:27