Re: Is there a pattern for creating an object with global scope?
Re: Is there a pattern for creating an object with global scope?
- Subject: Re: Is there a pattern for creating an object with global scope?
- From: Tom Davie <email@hidden>
- Date: Sat, 13 Apr 2013 13:57:15 +0100
On 13 Apr 2013, at 13:45, Uli Kusterer <email@hidden> wrote:
> On 13.04.2013, at 06:08, Jens Alfke <email@hidden> wrote:
>> On Apr 12, 2013, at 6:54 PM, Scott Ribe <email@hidden> wrote:
>>
>>> Yes, extremely easy, just "create" the var, as in:
>>>
>>> int gFoobar = 42;
>>
>> YT wants to create an object, which isn’t as straightforward because you can’t have an object literal in Objective-C. Instead you declare a global pointer and initialize it early on.
>>
>> MyClass* gMyObject;
>>
>> Then early at launch time:
>>
>> gMyObject = [[MyClass alloc] init];
>>
>> That second line could go into the -applicationDidFinishLaunching: method, which is the usual place where stuff gets initialized.
>
> Note that such a global variable has to be declared "outside any functions". I.e. best put it at the top of a .m file, right under the #includes. This is essentially what you use to implement a singleton like NSUserDefaults (unless you use dispatch_once, which might be a bit complicated for a beginner to understand, but would be the "best" solution I'm told).
>
> However, the bad thing about exposing such a global directly is that you have no control over who accesses it when. So if you create the object in applicationDidFinishLaunching: but some document class accesses it when a document is opened, they'll quietly do nothing because gMyObject is NIL (or it could crash if you call a method on it that doesn't return an object or number).
>
> A singleton solves that by having a method you go through to get at the singleton object:
>
> +(MyClass*) sharedMyClass
> {
> if (gMyObject == nil)
> gMyObject = [[MyClass alloc] init];
> return gMyObject;
> }
Just a heads up, if you really want global state, and really think that a singleton is the right way to go (I'm not gonna get into why you shouldn't think these things as the entire premise of the thread is that you do), then the singleton pattern is much better implemented as:
+ (instancetype)sharedMyClass
{
static MyClass *_sharedMyClass = nil;
static dispatch_once_t token;
dispatch_once(&token, ^
{
_sharedMyClass = [[MyClass alloc] init];
});
return _sharedMyClass;
}
This makes the access to the singleton thread safe when it's first created. Of course, you then get into the nightmare of trying to maintain thread safety when you have a chunk of global state lying around, but that's a whole different story.
Thanks
Tom Davie
_______________________________________________
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