Return to Snippet

Revision: 54255
at December 17, 2011 03:21 by neoline


Initial Code
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];

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

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

Initial Title
Global Variables in Objective-C (Singleton)

Initial Tags
c, iphone

Initial Language
Objective C