Re: Instance methods VS. Class methods
Re: Instance methods VS. Class methods
- Subject: Re: Instance methods VS. Class methods
- From: Andreas Monitzer <email@hidden>
- Date: Sat, 24 Nov 2001 08:51:37 +0100
On Saturday, November 24, 2001, at 05:19 , Matt Ronge wrote:
I've read through Apple's docs, read through Learning Cocoa, and I have
searched all over the web. Yet none of them have shed light on the
difference between instance methods and class methods?
Can someone give examples of why you would use one over the other? Is
there
something comparable in C++ to them? Is one of them just a private
method
identifer for use internally by the class?
For newbies coming from C++ (like I was once), it's best compared to the
reserved C++-word "static".
However, it's not really that way. In ObjC, there's one object per class
that is automatically generated and the one responsible to create
instances of the class.
So you can call [NSString alloc], since "alloc" is a class method. You
can't call [NSString init], because "init" is an instance method and
NSString is a class object.
The following is valid code (but results in a warning for whatever
reason):
@interface MyObject: NSObject {
int value;
}
+ (void)initialize;
@end
@implementation MyObject
+ (void)initialize {
value=10;
}
@end
Since that class object is full-blown, you can use the variables. It's
even possible to do the following:
+ (id)newInstance {
self=[[self alloc] init]; // replace self with a new instance
value=20; // set the value of the new instance
return [self autorelease];
}
But don't think about using that in production code :)
andy