Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set @property of a Singleton class

Currently i'm using a Property on the AppDelegate class.

Now, as my needs expend, I need more then 1 of these global property, so I thought to make a Singleton class that will hold the properties and will mange them. I found a lot of information about Singletons, but I couldn't figure out, is it possible to modify the property without having an Instance of the class?

For example:

@interface Tools : NSObject

@property (nonatomic,retain) NSDictionary* item;

... 

@end

I would like to do:

[Tools setItem:someDict];
someClass = [someClass alloc] initWithItem:[Tools getItem]];

All my ideas ended up with the problem that the class Tools has no instance. I've tried setting item to be static variable (not property), which worked, but i'm sure that this is not the right why to do it.

related but different question, Adding:

#import "Tools.h"

To the project-Prefix.pch file ,so the item properties will be available from everywhere on the project, Is a good idea?

like image 287
EladG Avatar asked Sep 20 '11 10:09

EladG


1 Answers

You are right in that you need an instance for using a singleton. But where is the problem?

[Tools sharedInstance].item = someDict; // or
[[Tools sharedInstance] setItem:someDict;

The sharedInstance method then assures proper instantiation of the one and only Tools instance. I got used to it. The alternative is a class member. You may look at this thread:

BOOL being reset to NO in init method

like image 128
Kay Avatar answered Oct 04 '22 14:10

Kay