On 14.04.2013, at 06:29, Steve Mills <[email protected]> wrote:
> 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.
If the C++ Steve wrote helps you understand things better, here's a 1-to-1
translation of that code to the equivalent in Objective C:
PreRun.h:
@interface PreRun : NSObject
{
BOOL theVariableYouWantToBeGlobal;
}
-(PreRun*) sharedInstance; // Usually a singleton access method is called
defaultX or sharedX, not GetInstance like in C++.
-(void) setVar: (BOOL)b;
-(BOOL) var; // You usually don't use GetX as the name for a
getter in Objective C. A 'get' prefix is used to indicate a method that has
return parameters.
@end
PreRun.m:
@implementation PreRun
-(PreRun*) instance
{
static PreRun* sSharedInstance = nil;
if( sSharedInstance == nil )
sSharedInstance = [[PreRun alloc] init];
return sSharedInstance;
}
-(void) setVar: (BOOL)b
{
theVariableYouWantToBeGlobal = b;
}
-(BOOL) var
{
return theVariableYouWantToBeGlobal;
}
@end
> In a file that wants to use that variable:
[[PreRun instance] setVar: YES];
As others mentioned, you could use dispatch_once for thread safety (but I don't
think threading is a topic you want to tackle at this point, save that for
later and save yourself a lot of pain and random bugs that sometimes happen and
sometimes don't). Also, you would probably use @property BOOL (assign) var; and
@synthesize var = theVariableYouWantToBeGlobal; to save yourself the work of
writing setVar:/var methods and declaring the instance variable
'theVariableYouWantToBeGlobal'.
Some people also believe in overriding -init, -retain, -release and
-retainCount to keep people from creating a second instance of this object, but
that's more defensive coding than necessary. I just mention it because it's the
moral equivalent to Steve's making the constructor private.
Cheers,
-- Uli Kusterer
"The Witnesses of TeachText are everywhere..."
http://www.masters-of-the-void.com
_______________________________________________
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]