Re: Several questions
Re: Several questions
- Subject: Re: Several questions
- From: Scott Anguish <email@hidden>
- Date: Fri, 6 Jul 2001 18:01:31 -0400
On Friday, July 6, 2001, at 03:28 AM, jgo wrote:
From: "John C. Randolph" <email@hidden>
Date: 2001 July 02 21:11:36 -0700
On Monday, 2001 July 02 at 18:26, Hisaoki Nishida wrote:
I have some general questions about Cocoa programming...
2. What's the difference between - and + (in method declarations)?
- means an instance method. + means a class method.
Well, I know what a class is, and I know what an instance is,
but what is an "instance method" as opposed to a "class method"?
I never considered the possibility that a method would be
instantiated, as contrasted with data members/instance variables.
The method isn't being instantiated...
A class method operates on the class, so there is no data to be
dealt with. Usually it's used to create an instance of the class in
some way. You actually call it on the class.. a really common example
would be alloc.. you call a class (say, NSObject) method alloc , and you
get back an instance of the object.
an instance method is something you'd call on an instantiated
object that has been created through a class method
For example
theArray=[NSMutableArray array]
that is a class method on NSMutableArray that will return a new
empty array.
[theArray addObject: someOtherObject]
that is calling an instance method.
does that make sense?
Another really common use for class methods is when you're
designing a singleton class.. one where you only want to have a single
instance of the class all the time. in this case you would call the
class method, and it would return an instance to work with, but not
necessarily a new one, this is usually handled using a static variable,
and having the class method create a new instance the first time it's
used, and then subsequently returning the same value any time it is
asked for one in the future.
Hmm.. I'm having a bit of a hard time finding an example of this in
the AppKit/Foundation.. maybe NSDistributedNotificationCenter
defaultCenter is one..
Ah.. NSWorkspace sharedWorkspace is a possible example..