Re: class variables and class methods
Re: class variables and class methods
- Subject: Re: class variables and class methods
- From: Glenn Andreas <email@hidden>
- Date: Wed, 7 Jan 2004 17:13:40 -0600
At 10:15 PM +0000 1/7/04, Robert Goldsmith wrote:
Hi everyone :)
Sorry if this is a simple question but it has been driving me up the wall :(
Those are the sorts that usually do - the hard ones you expect to be
difficult...
Maybe I was wrong to expect this but I thought class methods and
class variables would behave much like instance ones, but this does
not seem to be the case. Let me outline the problem:
Objective-C does not currently have class variables, so right there
is an issue.
Starting simple, I have class A, which has an instance method
(lookup) that refers to a static (so it won't inherit) class
variable called lookupTable (which is a c style array). Every
instance of class A uses the same lookup table. This works fine.
That is just a static variable, and not a class variable (since there
currently aren't such things).
Now, I create a subclass of A called As and define a new static
class variable in As with the same name, lookupTable. When I call
lookup in an instance of As, I get back details from the lookupTable
variable in A, not the one in As.
Is there any easy way to fix this?
No, not "easy", other than the way you just did it.
So far, I have found the only way is to access lookupTable via an
accessor method that must be repeated in every subclass of A. This
is not very good as it means repeating the accessor when, really, it
should just be inherited. On the other hand, at least the accessor
is small and not prone to have bugs in it :) It just seems very
messy and non oo :(
If you wanted to get uglier, but only once, you could define the
class accessor method to actually have a static dictionary that
mapped between the class and the specific value for each class. It
would make the accessor method ugly (and a bit slower) but it would
only have to be done once.
Note that a similar trick can be done to add pseudo-instance
variables to base classes that you don't have the source code for (by
adding a category to that class, and then having a dictionary mapping
instances of that class to the value for that pseudo-instance
variable accessor method).
OTOH, even if Objective-C did have class variables, those class
variables would be inherited by all subclasses, just like class
methods are inherited by all subclasses.
(One can certainly argue for something that doesn't get inherited but
rather gets cloned upon setting, which was doable in languages like
NewtonScript or Self, but not Objective-C).
--
Glenn Andreas email@hidden
Theldrow, Blobbo, Cythera, oh my!
Be good, and you will be lonesome
_______________________________________________
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.