2

According to Apple Doc:

"An instance method is a method whose execution is scoped to a particular instance of the class. In other words, before you call an instance method, you must first create an instance of the class. Instance methods are the most common type of method.

A class method is a method whose execution is scoped to the method’s class. It does not require an instance of an object to be the receiver of a message."

*So what really is "self" ? why it can receiver both class method and instance method ? So "before you call an instance method, you must first create an instance of the class" is wrong ? Example :

{ ...
[self method1];
//I'm doesn't create any instance of class//
[self method2];
}
-(void)method1 {
NSLog(@"this is a instance method");
}
+(void)method2 {
NSLog(@"this is a class method");
}
nhgrif
  • 61,578
  • 25
  • 134
  • 173
Joker
  • 21
  • 2
  • self is used to reference the object that is invoking a method. – Rohit Jul 15 '15 at 10:17
  • [This comment on an answer to another question](http://stackoverflow.com/questions/7290156/call-a-class-method-from-within-that-class#comment13044858_7290221) explains what you're asking better than any of the current questions. – nhgrif Jul 15 '15 at 12:05

3 Answers3

3

In Objective-C instances of a class are objects but there is also a class object too.

So, self is either one of two things.

If the scope of self is inside an instance method then self is an instance of the class.

If the scope of self is inside a class method then self is the class object.

In the second case you could replace self with the class name but this may break inheritance if you were to subclass the class for instance.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
1

self is the receiver of the method.

So obviously if you call an instance method, then that instance receives the method, so self is the instance. But if you call a class method, then the class receives the method, so self is the class.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • But you can't mix them. If self is an instance then you can't send it a class method selector and vice versa. The object self is not determined by the method you are sending it. – Fogmeister Jul 16 '15 at 09:00
0

Well, I think the documention is really clear. In order to call an instance method, you have to instantiate the object referenced by self first. So the self invocation in [self method1] refers to a particular instance of the class. On the other hand, you can see the self in [self method2] as a "placeholder" for the name of the class.

Dree
  • 702
  • 9
  • 29