目标C中的Sinlgeton对象 [英] Sinlgeton object in objective C
问题描述
我需要对目标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];
}
-
单例对象是否需要@synchronized块???
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] initWithDefault];
等待您的答复.
推荐答案
是的. Matt Gallagher有一个非常方便的宏,您可以使用它来为您的课程添加单例支持(您只需添加SYNTHESIZE_SINGLETON_FOR_CLASS(<class name> inside the implementation block)
:
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; \
}
这篇关于目标C中的Sinlgeton对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!