Sinlgeton object in objective C
I need some clarification regarding the singleton object implementation in Objective C. I have implemented the following code for the singleton object ..
static MyClass *instance = nil;
+(MyClass *)getInstance
{
@synchronised(self)
{
if(instance == nil)
{
instance = [[self alloc] init];
}
}
return instance;
}
-(void)dealloc
{
[instance release];
[super dealloc];
}
Does the singleton object requires @synchronised block ???
I have custom defined constructor in my class as follows:
-(id)initWithDefault ..
Does the following line of code creates an issue while allocating for instance
instance = [[self alloc] initWithDe开发者_开发知识库fault];
awaiting for your response.
Yes you should. There is a really handy macro by Matt Gallagher that you can use to add singleton support for your class (you just add a SYNTHESIZE_SINGLETON_FOR_CLASS(<class name> inside the implementation block)
:
#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; \
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return NSUIntegerMax; \
} \
\
- (id)autorelease \
{ \
return self; \
}
精彩评论