Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Best way to create a singleton class in Objective-C

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 437
    Comment on it

    There are different ways to create a singleton/shared instance of a class in Objective-C. Here I have explained two most preferred methods for it and both are thread safe.
    1) Using "@synthesize"

        #define SINGLETON_FOR_CLASS(yourclassname) \
         \
        static yourclassname *shared##yourclassname = nil; \
         \
        + (yourclassname *)shared##yourclassname \
        { \
            @synchronized(self) \
            { \
                if (shared##yourclassname == nil) \
                { \
                    shared##yourclassname = [[self alloc] init]; \
                } \
            } \
             \
            return shared##yourclassname; \
        } \
         \
    

    2 ) Using "dispatch_once" from GCD

       #define SINGLETON_FOR_CLASS(yourclassname)\
                + (id) shared##yourclassname {\
                static dispatch_once_t pred = 0;\
                __strong static id _sharedObject = nil;\
                dispatch_once(&pred, ^{\
                _sharedObject = [[self alloc] init];\
                });\
                return _sharedObject;\
                }
    

    Both the methods above are thread safe. There is only one difference between these two, dispatch_once is much faster than @synthesize.
    I have created these methods as a macro. To use any of the method import the macro file in your class for which you need to create a shared instance.
    Put following line in the header file of your class.
    +(id)sharedyourclassname;

    And in implementation class add following to create a singleton.

    SINGLETON_FOR_CLASS(yourclassname);

    Whatever class name you pass here it will create a singleton for that class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: