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 quest开发者_高级运维ion, 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?
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
As far as my knowledge about Objective-C is concerns, there is no such thing that you can call @property without creating an instance.
You can Refer How Do I declare Class-level Property in Objective-C
There is a discussion on class @properties in this ARC-related thread (the recommended way to do singletons with ARC is with class methods). Class variables don't exist yet, but I suggest you file a radar to up vote the feature.
精彩评论