Thursday, 11 April 2013

How to create singleton class in objective c

Some time you need to create only one instance of a class and you also want to restrict more than one instance of that class. In this situation you need to create singleton class.

Singleton Class  is a class which has one and only one object.

To create a singleton class in objective C first of all

Create a new class subclass of  NSObject and add the desired properties in .h file.


@interface User : NSObject
@property (nonatomic, retain) NSString *userName;
@property (nonatomic, retain) NSString *password;
@property (nonatomic, retain) NSString *status;
+ (id)CreateUser;
+ (id)getUser;

Here + sign indicates that methods are static. Its mean we can call these methods without creating instance of class.

Now go to .m file, synthesize  properties and implement method

@synthesize userName;
@synthesize password;
@synthesize status;

static User *user = nil;
#pragma mark Singleton Methods

+ (id)CreateUser {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        user = [[self alloc] init];
    return user;
+ (id)getUser {
    return user;

Here dispatch_once() is used to execute a block once and only once and it needs pointer to a dispatch_once_t that is used to test whether the block has completed or not.

You can use this code. Call createUser to create user and getUser to get already crated user. 

No comments:

Post a Comment