How to implement:
You can implement a singleton class in Objective-C using the following code:
DataManager.h
#import <foundation/Foundation.h> @interface DataManager : NSObject { NSString *someProperty; } @property (nonatomic, retain) NSString *someProperty; + (id)sharedManager; @end
DataManager.m
What this does is it defines a static variable called#import "DataManager.h" @implementationDataManager @synthesize someProperty; #pragma mark Singleton Methods+ (id)sharedManager { static DataManager *sharedDataManager = nil; @synchronized(self) { if (sharedDataManager == nil) sharedDataManager = [[self alloc] init]; } return sharedDataManager; }- (id)init { if (self = [super init]) { someProperty = [[NSString alloc] initWithString:@"Default Property Value"]; } return self; } @end
sharedDataManager which is then initialised once and only once in sharedManager. Then you can reference the singleton from anywhere by calling the following function:DataManager *sharedManager = [DataManager sharedManager];
No comments:
Post a Comment