Re: Several questions
Re: Several questions
- Subject: Re: Several questions
- From: Greg Titus <email@hidden>
- Date: Fri, 6 Jul 2001 14:40:35 -0700
On Friday, July 6, 2001, at 12:28 AM, jgo wrote:
>
> From: "John C. Randolph" <email@hidden>
>
>> 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"?
Well, an instance method is one that starts with a -, and a class method
is one that starts with a +. Wasn't that helpful? :-)
>
I never considered the possibility that a method would be
>
instantiated, as contrasted with data members/instance variables.
No, the distinction is between a method that can be called upon an
instance versus a method which can be called on a class. If you are
familiar with C++ or Java you can consider a class method as sort of a
'static' method in either of those languages.
So [NSString availableStringEncodings] is a class method because it is a
method called on the class object itself, while [aString
fastestEncoding] is an instance method - you call it on a specific
string instance, not the class itself. If you have a method which is
related to the class (e.g. the possible encodings for all strings) but
not related to any particular instance of the class, make it a class
method so you can call it without having to create a specific instance
if you want to. In Cocoa most class methods are methods that create
instances like +alloc, +stringWithCString:, et cetera, but they
certainly don't have to be (which is why I used
+availableStringEncodings as my example).
The difference between a class method in Objective-C and a static method
in Java/C++ is that Objective-C has true class objects. The class object
is an instance of a meta-class, so it is a real object in every respect.
You go through exactly the same sort of dynamic lookup and inheritance
and so on with class methods as you do with instance methods. Unlike in
C++/Java where static methods are really exactly the same as function
calls - they are statically bound at compile-time and not override-able.
C++/Java adds some of this into their introspection/reflection
additions, but it's kind of a hacked on afterthought instead of being
built into the language.
Hope this helps,
-Greg