Monday, December 21, 2015

Singletons in Objective-C

One of my most used design patterns when developing for iOS is the singleton pattern. It’s an extremely powerful way to share data between different parts of code without having to pass the data around manually. This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.
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
#import "DataManager.h"

@implementation DataManager

@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
What this does is it defines a static variable called 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