Re: Instance methods VS. Class methods
Re: Instance methods VS. Class methods
- Subject: Re: Instance methods VS. Class methods
- From: Ondra Cada <email@hidden>
- Date: Sat, 24 Nov 2001 13:04:23 +0100
Andreas,
>
>>>>> Andreas Monitzer (AM) wrote at Sat, 24 Nov 2001 08:51:37 +0100:
AM> The following is valid code (but results in a warning for whatever
AM> reason):
For the reason it should not be valid -- so far as I understand, it's
supported for legacy reasons only.
AM> Since that class object is full-blown, you can use the variables. It's
AM> even possible to do the following:
AM>
AM> + (id)newInstance {
AM> self=[[self alloc] init]; // replace self with a new instance
AM> value=20; // set the value of the new instance
AM> return [self autorelease];
AM> }
It's possible, but don't, don't, don't.
If you want the variable to belong to the class(*), use
@implementation Xxx
static int classVariable;
+(void)classMethod { classVariable=10; }
@end
If you want to access instance variables, do it indirectly:
@interface Yyy:... { int xx; } ... @end
@implementation Yyy
-(void)initWith:(int)x { ... xx=x; ... }
+(void)newInstanceWith:(int)x {
return [[[self alloc] initWith:x] autorelease];
}
@end
(*) actually, such variable does not belong just to the class, but also to
all its subclasses. Should you want to have a real class variable which
belongs to a class indeed (so that its value for a class and its subclass can
differ), you have to use something like a static NSDictionary with ids (or
class names) as keys. In practice though those real class variables are
extremely rarely needed.
---
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