Global Variables in Objective-C (Singleton)


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

How to make Global Variables (Singleton) in Objective-C


Copy this code and paste it in your HTML
  1. Step 1: Open your XCode project and add a new class.
  2.  
  3. In your XCode > ‘Group & Files’ colum > Right click on the classes folder > Click ‘Add > New File..’ > Select ‘Objective-C class’ (ensure its a sub class of NSObject) > Click ‘Next’ > Enter the new class name (in this example, GlobalData) > Finish
  4.  
  5. Step 2: The .h file
  6.  
  7. @interface GlobalData : NSObject {
  8. NSString *message; // global variable
  9. }
  10.  
  11. @property (nonatomic, retain) NSString *message;
  12.  
  13. + (GlobalData*)sharedGlobalData;
  14.  
  15. // global function
  16. - (void) myFunc;
  17.  
  18. @end
  19.  
  20.  
  21. Step 3: The .m file
  22.  
  23. #import "GlobalData.h"
  24.  
  25. @implementation GlobalData
  26. @synthesize message;
  27. static GlobalData *sharedGlobalData = nil;
  28.  
  29. + (GlobalData*)sharedGlobalData {
  30. if (sharedGlobalData == nil) {
  31. sharedGlobalData = [[super allocWithZone:NULL] init];
  32.  
  33. // initialize your variables here
  34. sharedGlobalData.message = @"Default Global Message";
  35. }
  36. return sharedGlobalData;
  37. }
  38.  
  39. + (id)allocWithZone:(NSZone *)zone {
  40. @synchronized(self)
  41. {
  42. if (sharedGlobalData == nil)
  43. {
  44. sharedGlobalData = [super allocWithZone:zone];
  45. return sharedGlobalData;
  46. }
  47. }
  48. return nil;
  49. }
  50.  
  51. - (id)copyWithZone:(NSZone *)zone {
  52. return self;
  53. }
  54.  
  55. - (id)retain {
  56. return self;
  57. }
  58.  
  59. - (NSUInteger)retainCount {
  60. return NSUIntegerMax; //denotes an object that cannot be released
  61. }
  62.  
  63. - (void)release {
  64. //do nothing
  65. }
  66.  
  67. - (id)autorelease {
  68. return self;
  69. }
  70.  
  71. // this is my global function
  72. - (void)myFunc {
  73. self.message = @"Some Random Text";
  74. }
  75. @end
  76.  
  77.  
  78. Access Global:
  79. #import "GlobalData.h"
  80.  
  81. Access Global Variable:
  82. [GlobalData sharedGlobalData].message
  83.  
  84. Access Global Function:
  85. [[GlobalData sharedGlobalData] myFunc];

URL: http://sree.cc/iphone/global-functions-and-variables-in-objective-c

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.