@interface MySingleton : NSObject {
// ...
}
+ (MySingleton *)sharedInstance;
// Interface
- (NSString *)helloWorld;
@end#import "MySingleton.h"
static MySingleton *sharedInstance = nil;
@implementation MySingleton
#pragma mark Singleton methods
+ (MySingleton *)sharedInstance {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[MySingleton alloc] init];
}
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance; // 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;
}
#pragma mark -
#pragma mark NSObject methods
- (id)init {
if (self = [super init]) {
// ...
}
return self;
}
- (void)dealloc {
// ...
[super dealloc];
}
#pragma mark -
#pragma mark Implementation
- (NSString *)helloWorld {
return @"Hello World!";
}
@end#import "MySingleton.h"
// ...
NSLog(@"Result for singleton method helloWorld: %@", [[MySingleton sharedInstance] helloWorld]);
阅读(5028) | 评论(0) | 转发(0) |