Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Singleton Classes

meowmix23Fmeowmix23F Posts: 144Tutorial Authors
edited January 2012 in iPhone SDK Tutorials
Have you ever wanted to share data between views, but couldn't figure it out for the life of you? Now, here's a solution. A singleton class. Any class can generate a reference (pointer) to the shared version of the class, which is only allocated once. You can then set values and retreive them, or write up any class methods you'd like.

Basically, instead of calling

myclass *instance = [[myclass alloc] init];

every time you want to reference a class (and bear in mind, it's a *new* instance of that class, so if you add variables to it the next time you allocate one of those classes it won't have the variables)

You'd call

myclass *instance = [myclass sharedInstance];

Then, any modifications to that instance change the entire thing, meaning that should you get another reference to +sharedInstance later it would still have the variables from before, because, in essence, it's the same instance! Should you want to share data, all you'd have to do is add a variable to the singleton's interface, such as an NSString.

NSString *myVariable

Then, you'd declare properties for it and synthesize it as usuaul.

From your other class, you'd include the header file for the singleton class (#import "singleton.h")
And then you'd just get a reference to the shared instance (using my example method below to create the instance),
and then change variables. Then, from another class, you can get a reference to the shared instance and look at what those variables are.

Here's a small example
// Singleton.h

@interface Singleton : NSObject 
{

NSMutableDictionary *keys;

}
@property (nonatomic, retain) NSMutableDictionary *keys;
+ (Singleton *)sharedSingleton;

As you can see, we have one "class" method called "sharedSingleton". It is a class method because it starts with a plus sign, instead of the usual minus sign. One thing about class methods is that they normally return autoreleased objects. In iPhone programming you've seen this in:

[NSUserDefaults standardUserDefaults]
[UIDevice currentDevice]
[UIScreen mainScreen]

etc.

If you make a pointer to one of them, it's automatically released (autorelease!)

Now, to our Singleton.m file
// singleton.m

static Singleton *shared = NULL;

@implementation Singleton

- (id)init
{
if ( self = [super init] )
{
self.keys = [[NSMutableDictionary alloc] init];
}
return self;

}

+ (Singleton *)sharedSingleton
{
@synchronize shared
{
if ( !shared || shared == NULL )
{
// allocate the shared instance, because it hasn't been done yet
shared = [[Singleton alloc] init];
}

return shared;
}
}

- (void)dealloc
{
NSLog(@"Deallocating singleton...");
[keys release];

[super dealloc];
}

@end

As you can see, we allocate a new "sharedInstance" if the current one is null.

Now, we just expose the keys as a property, and you basically have your own NSUserDefaults (a way of interacting between views).


Say, you have a variable from one view that you want to pass to another.

ie: score = @"500";

in the first view, you'd have to import singleton.h

then you'd say

Singleton *singleton = [Singleton sharedSingleton];
[singleton.keys setObject:score forKey:@"score"];

in your other view, you'd do this, only you'd use objectForKey on the keys property



anybody, feel free to post and correct something, as i've only used singleton's a few times (well custom ones atleast)
Post edited by meowmix23F on
·

Replies

  • chbeerchbeer Posts: 229Registered Users
    edited July 2009
    Have you heard of an app delegate? That's the singleton you should use for that, I think.
    Learn vocabularies on iPhone? <a href="http://iphone.chbeer.de/iVocabulary" target="_blank">iVocabulary</a>!
    ·
  • natanavranatanavra Posts: 56Registered Users
    edited July 2009
    chbeer wrote: »
    Have you heard of an app delegate? That's the singleton you should use for that, I think.

    That's not suggested.
    It's better to create your own singelton...
    Ummm by the way shouldn't you use @synchronize?
    ·
  • iomaticiomatic Posts: 19Registered Users
    edited July 2009
    Neat.

    Total newbie at programming in general, but understand basic concepts.

    How would you set up an array/sub-arrays of data, and pass one of the items in an array (or one of the items in a sub-array) to another class?

    What about SQLite?
    ·
  • meowmix23Fmeowmix23F Posts: 144Tutorial Authors
    edited July 2009
    Good catch.

    You should add @synchronize { } around the references to our actual singleton allocation, in case you have to reference it from different threads.
    ·
  • meowmix23Fmeowmix23F Posts: 144Tutorial Authors
    edited July 2009
    iomatic wrote: »
    Neat.

    Total newbie at programming in general, but understand basic concepts.

    How would you set up an array/sub-arrays of data, and pass one of the items in an array (or one of the items in a sub-array) to another class?

    What about SQLite?

    You can add array properties to the class, and add / delete objects from the array in different classes. SQLite is completely off topic, however, since this is more of an introduction than an application tutorial.
    ·
  • iomaticiomatic Posts: 19Registered Users
    edited August 2009
    If this is an introduction, can you please go into more detail starting from the ground up (without, of course, starting in basic math nor "How to launch a XCode" :))? That is, if someone has a little experience programming: What is a singleton, specifically? How does it share data (mechanically, specifically speaking)? That sort of stuff. A FAQ, if you will. THANKS!
    ·
  • meowmix23Fmeowmix23F Posts: 144Tutorial Authors
    edited August 2009
    iomatic wrote: »
    If this is an introduction, can you please go into more detail starting from the ground up (without, of course, starting in basic math nor "How to launch a XCode" :))? That is, if someone has a little experience programming: What is a singleton, specifically? How does it share data (mechanically, specifically speaking)? That sort of stuff. A FAQ, if you will. THANKS!

    I added more.
    ·
  • dpigeradpigera Posts: 1New Users
    edited July 2010
    Great explanation.. thanks a lot!
    ·
  • owltechowltech Posts: 1New Users
    edited September 2011
    :)
    meowmix23F wrote: »
    Have you ever wanted to share data between views, ...

    I implemented your code in a project of mine, and found minor syntax errors, at least using XCode 4:

    The "@synchronize shared" in the .m file should read "@synchronized (shared)".

    The reference in the description at the end about "objectForKey" should read "valueForKey".

    Thanks for the insight, the work and the coding sample. Works great!
    ·
  • rissvannrissvann Posts: 5New Users
    edited January 2012
    thankyou very much. i didn't picked it much but must be very useful in advance level programming
    ·
  • newDevnewDev Posts: 75Registered Users
    edited January 2012
    This is an example of how I make singletons:
    static RouteData *sharedData;
    
    +(RouteData*)sharedData{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (!sharedData) sharedData = [[RouteData alloc]init];
        });
        return sharedData;
    }
    

    The dispatch once token and block ensure that the singleton is only allocated once.
    <a href="http://itunes.apple.com/us/app/sir-charles-barkley/id448562136?mt=8" target="_blank">Sir Charles Barkley</a>
    ·
  • davidlxkdavidlxk Posts: 43Registered Users
    edited January 2012
    if anyone is interested in the registry pattern (which allows you to store a number of singletons) in obj c, i wrote a simple implementation of it few months back. You should check it out ~

    Registry pattern in Cocoa cocos2d for iPhone
    Drop Dem is out now! You should check it out at <a href="http://itunes.apple.com/us/app/drop-dem/id490101113" target="_blank">http://itunes.apple.com/us/app/drop-dem/id490101113</a><br />
    <br />
    You should follow Drop Dem on Twitter <a href="http://twit
    ·
Sign In or Register to comment.