Re: Followup - Re: Is there a pattern for creating an object with global scope?
Re: Followup - Re: Is there a pattern for creating an object with global scope?
- Subject: Re: Followup - Re: Is there a pattern for creating an object with global scope?
- From: Steve Mills <email@hidden>
- Date: Sat, 13 Apr 2013 23:29:26 -0500
On Apr 13, 2013, at 23:08:41, YT <email@hidden> wrote:
> int gFoobar = 42;
>
> Then reference it elsewhere as:
>
> extern int gFoobar;
>
> I understand that solution and its working for me right now. I have a PreRun Class that defines the object and I instantiate in main.m just before the line
> return NSApplicationMain(argc, (const char **)argv);
> runs in main.m.
Instead of doing it there, add an NSApplicationDelegate subclass and do your initialization in the applicationWillFinishLaunching method. Read up on that. This is all good stuff to learn if you want to write good Mac or iOS apps.
> The object instance persists the entire program run. THEN I simply extern the global var that holds the pointer to the object in all of the Class files where its required to access it.
>
> It may be a violation of OOP theory and application, it may be considered a kludge BUT it works right now. I am willing to move to a conventional OOP solution if I could figure out how.
Oh, that's easy, once you know how to make singletons. OK, I wouldn't call it easy, but it's the right thing to do.
PreRun.h:
class PreRun
{
private:
// Static variable that holds the only instance of this class:
static PreRun* instance;
// The variable:
bool theVariableYouWantToBeGlobal;
// Private ctor so nobody else can create this:
PreRun(void)
: theVariableYouWantToBeGlobal(false) // Inits the member var.
{} // Nothing else to do here.
public:
static PreRun* GetInstance(void)
{
if(instance == nil)
instance = new PreRun;
return instance;
}
void SetVar(const bool b) { theVariableYouWantToBeGlobal = b; }
bool GetVar(void) const { return theVariableYouWantToBeGlobal; }
};
PreRun.cpp:
// Automatic initializer sets the instance to nil:
bool PreRun::instance = nil;
In a file that wants to use that variable:
PreRun::GetInstance()->SetVar(true);
Now, this doesn't handle the case of threaded apps where multiple threads might be trying to set and/or get the value at the same time. That's a whole other discussion. And, you can always simplify this example by making the member var public instead of private and doing away with the Set/GetVar methods, but that's not good form either.
--
Steve Mills
Drummer, Mac geek
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden