खोज…


परिचय

बस यह सुनिश्चित करें कि आप इस धागे को पढ़ते हैं ( इसका उपयोग करने से पहले सिंगलनेट के बारे में क्या बुरा है? )।

ग्रैंड सेंट्रल डिस्पैच (GCD) का उपयोग करना

जीसीडी यह गारंटी देगा कि आपका सिंगलटन केवल एक बार त्वरित हो जाता है, भले ही इसे कई थ्रेड से कहा जाए। 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;
}

सिंगलटन वर्ग का निर्माण और आवंटन / init का उपयोग करके कई उदाहरणों को होने से भी रोकना।

हम सिंग्लटन वर्ग इस तरह से बना सकते हैं कि डेवलपर्स को अपने स्वयं के उदाहरण बनाने के बजाय साझा उदाहरण (सिंगलटन ऑब्जेक्ट) का उपयोग करने के लिए मजबूर किया जाए।

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

सिंगलटन का निर्माण करना और इसे आवंटित / init, नए का उपयोग करके कई उदाहरण होने से भी रोकना।

//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
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow