On Apr 13, 2013, at 23:08:41, YT <[email protected]> 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 protected])
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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]