Zoeken…


Invoering

Zorg ervoor dat je deze thread leest ( wat is er zo slecht aan singletons? ) Voordat je hem gebruikt.

Grand Central Dispatch (GCD) gebruiken

GCD garandeert dat uw singleton maar één keer wordt geïnstantieerd, zelfs als deze vanuit meerdere threads wordt aangeroepen. Voeg dit in een willekeurige klasse in voor een enkele instantie met de naam 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;
}

Singleton-klasse maken en ook voorkomen dat deze meerdere instanties heeft met alloc / init.

We kunnen de Singleton-klasse zo maken dat ontwikkelaars gedwongen worden de gedeelde instantie (singleton-object) te gebruiken in plaats van hun eigen instanties te maken.

@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];

Singleton maken en ook voorkomen dat het meerdere instanties heeft met alloc / init, nieuw.

//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
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow