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: Uli Kusterer <email@hidden>
- Date: Sun, 14 Apr 2013 18:39:30 +0200
On 14.04.2013, at 06:29, Steve Mills <email@hidden> 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@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