Re: Scoping of functions
Re: Scoping of functions
- Subject: Re: Scoping of functions
- From: Ondra Cada <email@hidden>
- Date: Thu, 30 May 2002 01:48:29 +0200
On Thursday, May 30, 2002, at 01:07 , Bill Bumgarner wrote:
If I declare...
static int foo;
... in Thingamahover.m and declare...
static int foo;
... in SubThingamahover.m, then the two foo are not the same.
Of course not, but this way you *have to make new accessor methods*:
// Thingamahover.m
static foo;
@implementation Thingamahover
+(int)foo { return foo; }
+(void)setFoo:(int)bar { foo=bar; }
@end
// SubThingamahover.m
static foo;
@implementation SubThingamahover:Thingamahover
+(int)foo { return foo; } // clumsy non-elegant and error-prone copy/paste
programming here!
+(void)setFoo:(int)bar { foo=bar; }
@end
Class variable -- a real one -- would offer inheritance though without
that. You should be able to do just
@implementation Blah:Thingamahover
@end
to be able to use foo in Blah. Well you are able to do, but they would
access the *same* data as Thingamahover:
[Thingamahover setFoo:3];
[Blah foo] is now 3
[Blah setFoo:5];
[Thingamahover foo] is now 5
Now, again, very very often this is what you really wanted, but it is *not*
a class variable. A class variable (emulated) is this:
static NSMutableDictionary *foo;
@implementation Thingamahover1
+(int)foo { return [[foo objectForKey:NSStringFromClass(self)] intValue];
}
+(void)setFoo:(int)bar {
if (!foo) foo=[[NSMutableDictionary alloc] init];
[foo setObject:[NSNumber numberWithInt:bar]
forKey:NSStringFromClass(self)];
}
@end
@implementation BlahBlah:Thingamahover1 @end
@implementation BlahBlahBlah:Thingamahover1 @end
@implementation BlahBlahBlahBlah:Blah @end
This way, each class (a) inherits foo/setFoo: without any extra effort, (b)
has *its own* foo value. Just to be sure and once more, you *rarely* need
this behaviour, but it is what class variable would do if there were any.
---
Ondra Cada
OCSoftware: email@hidden
http://www.ocs.cz
2K Development: email@hidden
http://www.2kdevelopment.cz
private email@hidden
http://www.ocs.cz/oc
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.