On Mon, Nov 2, 2009 at 12:29 AM, Kyle Sluder <[email protected]> wrote:
> On Sun, Nov 1, 2009 at 9:19 PM, John Joyce
> <[email protected]> wrote:
>> Is it possible to create an NSCharacterSet constant?
>
> No.  By definition, constants are assigned values at compile time.
> Objects other than strings can only be created at runtime.  There is
> no way around this fact.
>
>> Is it best just to declare a global constant string, then initialize an
>> NSCharacterSet during app initialization? It certainly seems that is the
>> only real option.
>
> Answers will vary.  You could use a static global variable which is
> assigned in +initialize, or you could use a static variable in a
> category on NSCharacterSet, or a number of other things.  Basically
> what you really want is a singleton, not a constant.
>
> I'm partial to the following construct:
>
> + (Foo *)sharedFoo {
>  static Foo *sharedFoo;
>  dispatch_once_t once;
>  dispatch_once(&once, ^{ sharedFoo = [[foo alloc] init]; }
>  return sharedfoo;
> }

Watch out! The 'once' variable must be declared static as well.
Without it, if you're unlucky to get a zero-filled 'once' every time
through, this call will appear to work but leak a new Foo every time
you call it.

Mike
_______________________________________________

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to