Last Updated: February 25, 2016
·
3.359K
· xehivs

Your own Objective-C shared object

Having shared object method in your class is the simplest way to use its single, common instance in various places.

Turning your class into shared object–capable, is quite simple operation based on two basic steps. I. e. for YourClass class.

Step One

In your @interface file (YourClass.h) declare prototype of class method (this little + sign in front of prototype) called sharedObject.

+ (YourClass *) sharedObject;

Step Two

Implement (@implementationYourClass.m) method prototyped in step one. In block passed to dispatch_once() initialize sharedObject and after it return sharedObject.

+ (YourClass *) sharedObject 
{
    static dispatch_once_t once;
    static YourClass *sharedObject;
    dispatch_once(&once, ^{
        sharedObject = [[self alloc] init];
    });
    return sharedObject;
}

Voilà!

4 Responses
Add your response

Hi,

  1. That is called singleton, not "best solution to control MVCs model"

  2. Why do you call it "Model"? Models in MVC pattern should not make use of any singleton or it does not make sense.

  3. For singleton initialization the @synchronized block is nowadays obsolete.

Use dispatch_once instead: http://stackoverflow.com/questions/9119042/why-does-apple-recommend-to-use-dispatch-once-for-implementing-the-singleton-pat

over 1 year ago ·

@alhafoudh It's just simple tip for beginners. If you're looking for magic singleton word, you still have it in tag list, Rest of your comment is… absolutely right. I'll simply correct this tip.

New knowledge is always a good thing. Thanks!

over 1 year ago ·

This creates a shared instance of an object. Not a singleton. Anyone could come along and instantiate a different instance of your class using using [[YourClass alloc] init]. In order to make it a true singleton you need to ensure that +sharedObject is the only way of getting an instance.

You can run into trouble if YourClass conforms to NSCopying, in which case you can get a different object just by copying your shared instance. Not to mention that if someone explicitly releases your shared instance it will disappear forever.

Instead of:

sharedObject = [[self alloc] init];

You should have:

sharedObject = [[super allocWithZone:NULL] init];

Then override allocWithZone: to return and retain the shared instance (unless using ARC). copyWithZone: should just return self.

If manually managing memory override retain and autorelease to return self, retainCount to return NSUIntegerMax, and release as a no-op.

over 1 year ago ·

@jeffremer Call it singleton–capable class. I don't think you should treat it so strictly and limit class to a true singleton. Who could come along and instantiate a different instance of your class in your own code?

For beginners tip, i think we can assume using ARC.

I'll correct title and introduction for you. Thanks for comment!

over 1 year ago ·