#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];