Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create Singleton class

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 941
    Comment on it

    Sometimes, we need access of some object /data/ variable globally throughout the App. In that case, creating a singleton class which can be accessed through out the app is helpful.

    App Delegate is a good example of singleton class. After googling for 2 days, i found a cool way to create singleton class using Macros. Let's suppose i have to create an HttpRequest Manager to handle all requests using only one instance .

    call following line where you have to want to create the singleton class object.

    SYNTHESIZESINGLETONFOR_CLASS(RequestManager);

    and following is the class SynthesizeSingleton.h

    #define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
     \
    static classname *shared##classname = nil; \
     \
    + (classname *)shared##classname \
    { \
        @synchronized(self) \
        { \
            if (shared##classname == nil) \
            { \
                shared##classname = [[self alloc] init]; \
            } \
        } \
         \
        return shared##classname; \
    } \
     \
    + (id)allocWithZone:(NSZone *)zone \
    { \
        @synchronized(self) \
        { \
            if (shared##classname == nil) \
            { \
                shared##classname = [super allocWithZone:zone]; \
                return shared##classname; \
            } \
        } \
         \
        return nil; \
    } \
     \
    - (id)copyWithZone:(NSZone *)zone \
    { \
        return self; \
    } \
     \
    

 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: