LoginSignup
2
2

More than 5 years have passed since last update.

Singleton in Objective-C

Last updated at Posted at 2015-03-06

Header file

Manager.h
@interface Manager : NSObject
+ (instancetype)sharedInstance;
@end

Method file

  • Prevent concurrent access from multiple thread by @synchronized or dispatch_once
  • Prevent multiple allocation by overriding allocWithZone
Manager.m
@implementation Manager

static Manager *_manager = nil;

+ (instancetype)sharedInstance {
    @synchronized(self) {
        if(!_manager) {
            (void)[[self alloc] init];
        }
    }
    return _manager;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if(!_manager) {
            _manager = [super allocWithZone:zone];
        }
    }
    return _manager;
}
@end

or

Manager.m
@implementation Manager

static Manager *_manager = nil;

+ (instancetype)sharedInstance {
    static dispath_once_t onceToken;
    dispatch_once(&onceToken, ^{
        (void)[[self alloc] init];
    });
    return _manager;
}

+ (id)allocWithZone:(NSZone *)zone {
    static dispath_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [super allocWithZone:zone];
    });
    return _manager;
}
@end

Access

[Manager sharedInstance].property
[[Manager sharedInstance] method];

References
http://qiita.com/yuky_az/items/27031ec5ca55a95d6209
http://programming-ios.com/objective-c-singleton/
http://news.mynavi.jp/column/objc/051/

2
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2