Assume you have a Singleton
Constants class, instance of which you'd like to use throughout your application.
In someClass
, therefore we can reference [Constants instance] someCleverConstant];
Typing this gets old really quick and it would be nice to get a shortcut to the instance.
someClass
, we can declare @property (nonatomic, weak, readonly) Constants *constants;
-(Constants*) constants { if (constants == nil) constants = [Constants instance]; return constants; }
This way in someClass, therefore we can reference constants.someCleverConstant;
instead
A few questions on this:
weak
?Thank you for your time.
You could just create a global pointer to your singleton, like NSApp
for [NSApplication sharedApplication]
.
Presumably you've already got something like
static Constants * defaultInstance = nil;
at the top of your implementation file. If you remove the static
, and declare the variable in your header (keeping the definition in the .m file):
@interface Constants : NSObject
// etc.
@end
extern Constants * defaultInstance;
You can then access the singleton instance via the name defaultInstance
(probably want to change that name, though) in any file that imports the header (which you must be doing anyways). You'll have to call your singleton setup method (+instance
or whatever) somewhere very early in your program, such as -applicationDidFinishLaunching
to be sure that the pointer is set before you use it.
- Is what I described a reasonable approach?
I think there are other, better approaches, described above and in Paul.s's answer.
- Is it correct to declare a property
weak
?
Yes, the class that has this pointer doesn't need to own it, because the singleton owns itself;
- Is there any performance concerns with what i have described? Would it actually be better to call instance directly?
Either way, [Constants instance]
or self.constants
you're doing a message send. The first time you do self.constants
, you're doing two. None of this should be a real concern, though.
- Consider a situation where you have 20 classes, each needing it's own pointer to
Constants
instance. Would this approach work then?
To me, it seems unwieldy and inelegant.