Singleton Skeleton


/ Published in: Objective C
Save to your folder(s)

Credit: http://iphone.galloway.me.uk/iphone-sdktutorials/singleton-classes/


Copy this code and paste it in your HTML
  1. //MyManager.h
  2.  
  3. #import <foundation/Foundation.h>
  4.  
  5. @interface MyManager : NSObject {
  6. NSString *someProperty;
  7. }
  8.  
  9. @property (nonatomic, retain) NSString *someProperty;
  10.  
  11. + (id)sharedManager;
  12.  
  13. @end
  14.  
  15. //MyManager.m
  16.  
  17. #import "MyManager.h"
  18.  
  19. static MyManager *sharedMyManager = nil;
  20.  
  21. @implementation MyManager
  22.  
  23. @synthesize someProperty;
  24.  
  25. #pragma mark Singleton Methods
  26. + (id)sharedManager {
  27. @synchronized(self) {
  28. if(sharedMyManager == nil)
  29. sharedMyManager = [[super allocWithZone:NULL] init];
  30. }
  31. return sharedMyManager;
  32. }
  33. + (id)allocWithZone:(NSZone *)zone {
  34. return [[self sharedManager] retain];
  35. }
  36. - (id)copyWithZone:(NSZone *)zone {
  37. return self;
  38. }
  39. - (id)retain {
  40. return self;
  41. }
  42. - (unsigned)retainCount {
  43. return UINT_MAX; //denotes an object that cannot be released
  44. }
  45. - (void)release {
  46. // never release
  47. }
  48. - (id)autorelease {
  49. return self;
  50. }
  51. - (id)init {
  52. if (self = [super init]) {
  53. someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
  54. }
  55. return self;
  56. }
  57. - (void)dealloc {
  58. // Should never be called, but just here for clarity really.
  59. [someProperty release];
  60. [super dealloc];
  61. }
  62.  
  63. @end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.