Michael
Michael

Reputation: 1030

Why can't I use the classname instead of self in objective c

It's just something which is not logical for me. Sure it's useful to call methods within in a class by the self-keyword. But why isn't it possible calling it by the own classname??

e.g. [MyClassWhereIAmActuallyIn anyRandomMethod]; instead of [self anyRandomMethod];

Upvotes: 0

Views: 54

Answers (3)

Wain
Wain

Reputation: 119031

In OOP this is the difference between the class object and an instance of that class object. When you create a method, you specify whether it is a class method (+) or an instance method (-). Once the method is defined you need to call it in the appropriate way (on the class object or on an instance of that class).

Upvotes: 0

Joride
Joride

Reputation: 3763

You can call class method ('+') like that. Self is a pointer to an instance of your class in instance methods ('-'), self points to the singleton Class-object when you are in class methods ('+').

Upvotes: 1

Dirk
Dirk

Reputation: 31061

Because that has a different meaning.

[self someMethod]

sends someMethod to the object, whose reference is stored in the (slightly magic) variable self.

[SomeClass someMethod]

sends someMethod to the class object (yes, classes are objects, too), which contains the meta-information for class SomeClass.

Two different objects ("receivers"). Also note, that there are class methods in Objective-C (i.e., you can take advantage of the fact, that classes are objects, and define new methods for them). Observe:

@interface SomeClass
    - (void) someMethod;
    + (void) someMethod;
@end

These are completely different methods, intended for completely different receivers. The method tagged with - is an instance method (will be used, e.g., with self). The method tagged with + is a class method (and will be used with the class object).

Upvotes: 2

Related Questions