Created
June 27, 2012 00:17
-
-
Save jacksonfdam/3000412 to your computer and use it in GitHub Desktop.
Global Variables in Objective-C (Singleton)
This file contains hidden or 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
URL: http://sree.cc/iphone/global-functions-and-variables-in-objective-c | |
How to make Global Variables (Singleton) in Objective-C | |
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 | |
@interface GlobalData : NSObject { | |
NSString *message; // global variable | |
} | |
@property (nonatomic, retain) NSString *message; | |
+ (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]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This help me so much! Thank you!