Re: observing dealloc
Re: observing dealloc
- Subject: Re: observing dealloc
- From: Ken Tozier <email@hidden>
- Date: Tue, 29 May 2007 01:22:48 -0400
On May 29, 2007, at 12:28 AM, Chris Suter wrote:
No.
As others have suggested, why don't you just do something like the
following?
+ GlobalVarType *)globalVar
{
static GlobalVarType *globalVar;
if (!globalVar)
globleVar = [[[GlobalVarType alloc] init];
return globalVar;
}
This obviously isn't thread-safe; you'd have to add any thread
safety you might want.
Trying to generalise this would be just making things more
complicated for no real gain.
The main reason is that with a generalized mechanism, there's no
possibility for static variable name collisions. Many different
classes could all have a "gFoo" global without having to dream up a
different name for each class. Secondly, with a standard accessor
like "globalForKey", there's no need to create individual accessors
like you did or clutter up code with all those unique variable names.
Just define a set of keys that can be reused in many classes and
fetch corresponding globals with these keys.
For example:
NSColor *currentColor = (selected) ? [self globalForKey:
@"backgroundColor"] : [self globalForKey: @"foregroundColor"] ;
As opposed to:
NSColor *currentColor = (selected) ? gMyClassBackgroundColor :
gMyClassForegroundColor ;
Third, it's cleaner to implement.
Compare this:
int gMyClassIntGlobal = 0;
float gMyClassFloatGlobal = 0;
NSString *gMyClassStringGlobal = nil;
NSMutableDictionary *gMyClassDictGlobal = nil;
BOOL gMyClassGlobalsInitialized = NO;
+ (void) initialize
{
if (! gMyClassGlobalsInitialized )
{
gMyClassIntGlobal = 1;
gMyClassFloatGlobal = 3.1415926535;
gMyClassStringGlobal = @"bobo the wonder pig";
gMyClassDictGlobal = [[NSMutableDictionary dictionary] retain];
gMyClassGlobalsInitialized = YES;
}
}
To this:
+ (void) initialize
{
if (![MyObject globalsInitialized])
{
[MyObject setGlobal: [NSNumber numberWithInt: 1] forKey:
@"global_int"];
[MyObject setGlobal: [NSNumber numberWithFloat: 3.1415926535]
forKey: @"global_float"];
[MyObject setGlobal: @"bobo the wonder pig" forKey: @"global_string"];
[MyObject setGlobal: [[[NSMutableDictionary dictionary] retain]
forKey: @"global_dict"];
}
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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