Advertise Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Your First iPhone App
($1.99)

iPhone Code Generator
($9.99)

Calcuccino Programmers' Calculator
($2.99)

DataFon(Build Apps on Windows)
(free)

Infinote Pinboard for Todos and Notes
(free)

picplz
(free)

poG
($2.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Tutorials

Reply
 
LinkBack Thread Tools Display Modes
Old 07-24-2009, 10:35 PM   #1 (permalink)
Tutorial Author
 
Join Date: Jan 2009
Posts: 143
Default Singleton Classes

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

Code:
// 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

Code:
// 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)

Last edited by meowmix23F; 08-02-2009 at 10:55 AM.
meowmix23F is offline   Reply With Quote
Old 07-25-2009, 12:58 AM   #2 (permalink)
iPhone App Developer
 
chbeer's Avatar
 
Join Date: Sep 2008
Location: Berlin, Germany
Posts: 229
Default

Have you heard of an app delegate? That's the singleton you should use for that, I think.
__________________
Learn vocabularies on iPhone? iVocabulary!
chbeer is offline   Reply With Quote
Old 07-30-2009, 11:17 AM   #3 (permalink)
Registered Member
 
Join Date: Oct 2008
Posts: 56
Default

Quote:
Originally Posted by chbeer View Post
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?
natanavra is offline   Reply With Quote
Old 07-30-2009, 12:56 PM   #4 (permalink)
New Member
 
Join Date: Jul 2009
Posts: 19
Default

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?
iomatic is offline   Reply With Quote
Old 07-31-2009, 01:38 PM   #5 (permalink)
Tutorial Author
 
Join Date: Jan 2009
Posts: 143
Default

Good catch.

You should add @synchronize { } around the references to our actual singleton allocation, in case you have to reference it from different threads.
meowmix23F is offline   Reply With Quote
Old 07-31-2009, 01:40 PM   #6 (permalink)
Tutorial Author
 
Join Date: Jan 2009
Posts: 143
Default

Quote:
Originally Posted by iomatic View Post
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.
meowmix23F is offline   Reply With Quote
Old 08-01-2009, 12:43 PM   #7 (permalink)
New Member
 
Join Date: Jul 2009
Posts: 19
Default

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!
iomatic is offline   Reply With Quote
Old 08-02-2009, 10:52 AM   #8 (permalink)
Tutorial Author
 
Join Date: Jan 2009
Posts: 143
Default

Quote:
Originally Posted by iomatic View Post
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.
meowmix23F is offline   Reply With Quote
Old 07-23-2010, 03:36 PM   #9 (permalink)
Registered Member
 
Join Date: Jul 2010
Posts: 1
Default Awesome

Great explanation.. thanks a lot!
dpigera is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are On
Pingbacks are On
Refbacks are On


» Advertisements
» Stats
Members: 51,375
Threads: 52,831
Posts: 225,479
Top Poster: BrianSlick (3,576)
Welcome to our newest member, darrentousignant
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 02:32 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0