Szukaj…


Wprowadzenie

Upewnij się, że przeczytałeś ten wątek ( Co jest takiego złego w singletonach? ) Przed jego użyciem.

Korzystanie z Grand Central Dispatch (GCD)

GCD zagwarantuje, że twój singleton zostanie utworzony tylko raz, nawet jeśli zostanie wywołany z wielu wątków. Wstaw to do dowolnej klasy dla instancji singleton o nazwie shared .

+ (instancetype)shared {

    // Variable that will point to the singleton instance. The `static`
    // modifier makes it behave like a global variable: the value assigned
    // to it will "survive" the method call.
    static id _shared;

    static dispatch_once_t _onceToken;
    dispatch_once(&_onceToken, ^{

        // This block is only executed once, in a thread-safe way.
        // Create the instance and assign it to the static variable.
        _shared = [self new];
    });

    return _shared;
}

Tworzenie klasy Singleton, a także zapobieganie wielu instancjom za pomocą przydziału / init.

Możemy stworzyć klasę Singleton w taki sposób, że programiści są zmuszeni do korzystania ze współużytkowanej instancji (obiektu singleton) zamiast tworzenia własnych instancji.

@implementation MySingletonClass

+ (instancetype)sharedInstance
{
    static MySingletonClass *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc] initClass];
    });
    
    return _sharedInstance;
}

-(instancetype)initClass
{
    self = [super init];
    if(self)
    {
        //Do any additional initialization if required
    }
    return self;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"Not designated initializer"
                                   reason:@"Use [MySingletonClass sharedInstance]"
                                 userInfo:nil];
    return nil;
}
@end



/*Following line will throw an exception 
  with the Reason:"Use [MySingletonClass sharedInstance]" 
  when tried to alloc/init directly instead of using sharedInstance */
MySingletonClass *mySingletonClass = [[MySingletonClass alloc] init];

Tworzenie singletonu, a także zapobieganie wielu instancjom przy użyciu alokacji / init, nowe.

//MySingletonClass.h
@interface MYSingletonClass : NSObject

+ (instancetype)sharedInstance;

-(instancetype)init NS_UNAVAILABLE;

-(instancetype)new NS_UNAVAILABLE;

@end

//MySingletonClass.m

@implementation MySingletonClass

+ (instancetype)sharedInstance
{
    static MySingletonClass *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[self alloc]init];
    });
    
    return _sharedInstance;
}
-(instancetype)init
{
    self = [super init];
    if(self)
    {
        //Do any additional initialization if required
    }
    return self;
}
@end


Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow