0

I trying to implement singleton design pattern in objective C. Here is my code

In .h file

#import <Foundation/Foundation.h>
@interface BSCustomClass : NSObject
{
    NSString *string;
}
@property (nonatomic,strong)NSString *string;
@end 

In .m file

#import "BSCustomClass.h"
@implementation BSCustomClass
static int i;
static BSCustomClass* object;
@synthesize string;
-(id)init
{
    if(i==0)
    {
        object=[super init];
        i=1;
        object.string=@"tunvir Rahman";       
    }
    return object;
}
@end

Now if i want to create object of BSCustomClass from main using alloc and init then it will call is own init method and checks the static variable i. If i=0 then it is assumed that no object is created so far and create an object and after that it will return the address of the previous object for all object for the class BSCustomClass. Is this a correct implementation of singleton?? Thanks

Tunvir Rahman Tusher
  • 6,421
  • 2
  • 37
  • 32

2 Answers2

4

You should be using dispatch_once instead of the static int and a class method like "singleton" or "sharedInstance" instead of alloc-init. For a more detailed explanation I refer you do "Singletons: You're doing them wrong". Code from that post

+(MyClass *)singleton {
    static dispatch_once_t pred;
    static MyClass *shared = nil;

    dispatch_once(&pred, ^{
        shared = [[MyClass alloc] init];
    });
    return shared;
}
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
0

Singletons in Objective-C are implemented like this :

+(id)sharedInstance {
    static id instance = NULL;
    if (instance == NULL) instance = [[YourClassName alloc] init];
    return instance;
}

If there's any chance that it might be called from multiple threads, use David's solution instead.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
  • In many blog i have been suggested to avoid singleton. But it seems very useful to me! if i want to pass data to between object singleton is very useful and i think quite efficient. is there any detail in this matter. Thanks. – Tunvir Rahman Tusher Apr 21 '13 at 07:45