arkilis
5/17/2017 - 9:40 PM

singleton in objective-c

singleton in objective-c


// item.h
#import <Foundation/Foundation.h>

@interface Item : NSObject

+(instancetype)sharedInstance;

@end



// item.m
#import "Item.h"

static id _instance;

@implementation Item

+(instancetype)sharedInstance{
    if (_instance == nil) { // to avoid being created twice
        @synchronized(self) {
            if (_instance == nil) { // @synchronized() directive locks a section of code for use by a single thread.
                _instance = [[self alloc] init];
            }
        }
    }
    return _instance;
}

+(id)allocWithZone:(struct _NSZone *)zone{
    if (_instance == nil) {
        @synchronized(self) {
            if (_instance == nil) {
                _instance = [super allocWithZone:zone];
            }
        }
    }
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone{
    return _instance;
}

@end

```

// So do the fowllowing calls will get the same object/instance address:


Item *item1 = [[Item alloc]init];
Item *item2 = [Item sharedInstance];
Item *item3 = [item1 copy];