design patterns - What should my Objective-C singleton look like? -
my singleton accessor method variant of:
static myclass *ginstance = null; + (myclass *)instance { @synchronized(self) { if (ginstance == null) ginstance = [[self alloc] init]; } return(ginstance); }
what doing improve this?
another option use +(void)initialize
method. documentation:
the runtime sends
initialize
each class in program 1 time before class, or class inherits it, sent first message within program. (thus method may never invoked if class not used.) runtime sendsinitialize
message classes in thread-safe manner. superclasses receive message before subclasses.
so akin this:
static mysingleton *sharedsingleton; + (void)initialize { static bool initialized = no; if(!initialized) { initialized = yes; sharedsingleton = [[mysingleton alloc] init]; } }
Comments
Post a Comment