Created
May 6, 2011 04:31
-
-
Save jsok/958447 to your computer and use it in GitHub Desktop.
Singleton Class template (credits go to http://iphone.galloway.me.uk/iphone-sdktutorials/singleton-classes/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface MyManager : NSObject { | |
NSString *someProperty; | |
} | |
@property (nonatomic, retain) NSString *someProperty; | |
+ (id)sharedManager; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "MyManager.h" | |
static MyManager *sharedMyManager = nil; | |
@implementation MyManager | |
@synthesize someProperty; | |
#pragma mark Singleton Methods | |
+ (id)sharedManager { | |
@synchronized(self) { | |
if(sharedMyManager == nil) | |
sharedMyManager = [[super allocWithZone:NULL] init]; | |
} | |
return sharedMyManager; | |
} | |
+ (id)allocWithZone:(NSZone *)zone { | |
return [[self sharedManager] retain]; | |
} | |
- (id)copyWithZone:(NSZone *)zone { | |
return self; | |
} | |
- (id)retain { | |
return self; | |
} | |
- (unsigned)retainCount { | |
return NSUIntegerMax; //denotes an object that cannot be released | |
} | |
- (void)release { | |
// never release | |
} | |
- (id)autorelease { | |
return self; | |
} | |
- (id)init { | |
if (self = [super init]) { | |
someProperty = [[NSString alloc] initWithString:@"Default Property Value"]; | |
} | |
return self; | |
} | |
- (void)dealloc { | |
// Should never be called, but just here for clarity really. | |
[someProperty release]; | |
[super dealloc]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment