/ Published in: Objective C
How to make Global Variables (Singleton) in Objective-C
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
Step 1: Open your XCode project and add a new class. 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 Step 2: The .h file } + (GlobalData*)sharedGlobalData; // global function - (void) myFunc; @end Step 3: The .m file #import "GlobalData.h" @implementation GlobalData @synthesize message; static GlobalData *sharedGlobalData = nil; + (GlobalData*)sharedGlobalData { if (sharedGlobalData == nil) { sharedGlobalData = [[super allocWithZone:NULL] init]; // initialize your variables here sharedGlobalData.message = @"Default Global Message"; } return sharedGlobalData; } + (id)allocWithZone:(NSZone *)zone { @synchronized(self) { if (sharedGlobalData == nil) { sharedGlobalData = [super allocWithZone:zone]; return sharedGlobalData; } } return nil; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; //denotes an object that cannot be released } - (void)release { //do nothing } - (id)autorelease { return self; } // this is my global function - (void)myFunc { self.message = @"Some Random Text"; } @end Access Global: #import "GlobalData.h" Access Global Variable: [GlobalData sharedGlobalData].message Access Global Function: [[GlobalData sharedGlobalData] myFunc];
URL: http://sree.cc/iphone/global-functions-and-variables-in-objective-c