Objective-C单例实现

#ifndef RadishNinja_Singleton_h
#define RadishNinja_Singleton_h

// 单例声明(在@interface中)
#define SingletonDeclare(className)\
+(className*) singleton


// 单例实现(@implementation中)
#define SingletionImplement(className)      \
static className* _shared##className = nil; \
+(className*) singleton                     \
{                                           \
	@synchronized([className class])        \
	{                                       \
		if (!_shared##className)            \
			[[className alloc] init];            \
                                            \
		return _shared##className;          \
	}                                       \
                                            \
	return nil;                             \
}                                           \
                                            \
+(id)alloc\
{                                           \
	@synchronized([className class])        \
	{                                       \
		NSAssert(_shared##className == nil, @"Attempted to allocate a second instance of a singleton.");\
		_shared##className = [super alloc];     \
		return _shared##className;              \
	}                                           \
                                                \
	return nil;                                 \
}\


#endif


例子:

@interface myClass : NSObject

SingletonDeclare(myClass);

-(void) doSomething;

@end

@implementation myClass

SingletionImplement(myClass);

-(void) doSomething {
    NSLog(@"Are you sure you're a programing monkey?");
}

@end


调用
[[myClass singleton] doSomething];



posted on 2012-05-04 15:51  几百人有爱  阅读(142)  评论(0编辑  收藏  举报