Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9228313
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T05:17:26+00:00 2026-06-18T05:17:26+00:00

I want to have a thread safe, ARC compatible singleton, but is seems to

  • 0

I want to have a thread safe, ARC compatible singleton, but is seems to me that the most common example of singleton that I find, an example pasted here:

+ (MyClass *)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

doesn’t stops other developer from calling [[MyClass alloc] init] and overriding the desired flow.
What is the proper way to handle it (apart from throwing exception in init)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T05:17:28+00:00Added an answer on June 18, 2026 at 5:17 am

    you also have to override the +alloc method to avoid to allocate more than one instance of the singleton.

    EDIT#3: well, I really know what the official documentation says about overriding the +alloc method, but to achieve the asked benefit there is no way to avoid it. personally I don’t agree to do it but it can provide the desired result.

    it would be like this:

    static MyClass *_sharedInstance = nil;
    static BOOL _bypassAllocMethod = TRUE;
    
    + (id)sharedInstance {
        @synchronized([MyClass class]) {
             if (_sharedInstance == nil) {
                  _sharedInstance = [[MyClass alloc] init];
             }
        }
        return _sharedInstance;
    }
    
    + (id)alloc {
        @synchronized([MyClass class]) {
             _bypassAllocMethod = FALSE; // EDIT #2
             if (_sharedInstance == nil) {
                  _sharedInstance = [super alloc];
                  return _sharedInstance;
             } else {
                  // EDIT #1 : you could throw an exception here to avoid the double allocation of the singleton class
                  @throw [NSException exceptionWithName:[NSString stringWithFormat:@"<%@: %p> Double allocation issue", [_sharedInstance class], _sharedInstance] reason:@"You cannot allocate the singeton class twice or more." userInfo:nil];
             }
        }
        return nil;
    }
    
    // EDIT #2 : the init method
    - (id)init {
        if (_bypassAllocMethod)
            @throw [NSException exceptionWithName:@"invalid allocation" reason:@"invalid allocation" userInfo:nil];
    
        if (self = [super init]) {
        }
    
        return self
    }
    

    EDIT #1

    you don’t definitely need to throw an exception here but it is much more visual feedback for the developers of they use your class in wrong way, than sending back a simple nil pointer.

    EDIT #2

    I’ve added a simple trick to avoid the developers instantiate the class to bypass the modified +alloc method, in that case the allocation will work well but the -init will throw an exception.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to have a generic thread safe collection and I saw that the
I have a Singleton class that uses the thread-safe Singleton pattern from Jon Skeet
I have a map that i want to update from a separate thread. Im
i have a mainFrame that contains panel. i want in this panel a thread
I have a blocking queue of objects. I want to write a thread that
I have a Concurrency::concurrent_vector and want to push_back thread safe a new element only
I want to use boost::call_once() to achieve a thread-safe lazy-construction singleton scenario, however, the
We know that the dateformat classes are not thread safe. I have a multi-threaded
I want to have thread save method that returns a unique current Timestamp.Even when
I am writing an Objective-C class that I want to be thread safe. To

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.