官方参考:
http://www.apple.com.cn/developer/mac/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/chapter_3_section_10.html
一个单例模式实现的代码:
.h
#import <Foundation/Foundation.h> @interface Singleton : NSObject { } + (Singleton *) sharedInstance; @end
.m
#import "Singleton.h"
@implementation Singleton
static Singleton * _singleton = nil;
+ (Singleton *) sharedInstance
{
@synchronized(self) {
if(_singleton == nil){
_singleton = [[super allocWithZone:NULL] init];
}
}
return _singleton;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (_singleton == nil) {
_singleton = [super allocWithZone:zone];
return _singleton; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
@end