×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Objective-C
Posted by: Davide
Added: Oct 10, 2011 11:25 AM
Modified: Oct 10, 2011 11:26 AM
Views: 79
  1. static MySingleton *sharedInstance = nil;
  2.  
  3. + (void)initialize
  4. {
  5.     if (sharedInstance == nil)
  6.         sharedInstance = [[self alloc] init];
  7. }
  8.  
  9. + (id)sharedMySingleton
  10. {
  11.     //Already set by +initialize.
  12.     return sharedInstance;
  13. }
  14.  
  15. + (id)allocWithZone:(NSZone*)zone
  16. {
  17.     //Usually already set by +initialize.
  18.     @synchronized(self) {
  19.         if (sharedInstance) {
  20.             //The caller expects to receive a new object, so implicitly retain it
  21.             //to balance out the eventual release message.
  22.             return [sharedInstance retain];
  23.         } else {
  24.             //When not already set, +initialize is our caller.
  25.             //It's creating the shared instance, let this go through.
  26.             return [super allocWithZone:zone];
  27.         }
  28.     }
  29. }
  30.  
  31. - (id)init
  32. {
  33.     //If sharedInstance is nil, +initialize is our caller, so initialize the instance.
  34.     //If it is not nil, simply return the instance without re-initializing it.
  35.     if (sharedInstance == nil) {
  36.     self = [super init];
  37.     if (self) {
  38.             //Initialize the instance here.
  39.         }
  40.     }
  41.     return self;
  42. }
  43.  
  44. - (id)copyWithZone:(NSZone*)zone
  45. {
  46.     return self;
  47. }
  48.  
  49. - (id)retain
  50. {
  51.     return self;
  52. }
  53.  
  54. - (unsigned)retainCount
  55. {
  56.     return UINT_MAX; // denotes an object that cannot be released
  57. }
  58.  
  59. - (void)release
  60. {
  61.     // do nothing
  62. }
  63.  
  64. - (id)autorelease
  65. {
  66.     return self;
  67. }
  68.