By Mert

2009-08-21 11:50:45 8 Comments

What does self mean in Objective-C? When and where should I use it? Is it similar to this in Java?


@Amin Negm-Awad 2017-10-23 08:36:49

Wow, that many half-correct answers and misleading hints. This let me answer the Q even there is a accepted answer for years:

First of all: It is really hard to compare a concept of messaging/calling in the context of an early binding, static typing language as Java with a late binding, dynamically typing languages as Objective-C. At one point this will break. I would say: No, this is not similiar, since the typing and dispatching concepts of both language are fundamental different so nothing can be similar to the other one. However, …

Then we should differ between the "two sides" of self.

A. Using self

When you use it in a message, it is simply an object reference as any other:

[self doSomething];
[anotherObject doSomething];

Technically both lines works identically (accept of having a different receiver, of course). This especially means, that the first line does not lead to an execution of a method inside the class of self, because self does not necessarily refer to "that class". As every message inside Objective-C (single exception: messages to super)this can lead to the execution of a method in a subclass:

@interface A : NSObject
- (void)doSomething;
- (void)doAnotherThing;

- (void)doSomething
   [self doAntoherThing];
- (void)doAnotherThing
   NSLog( @"A" );

@interface B : A
- (void)doSomething; // Not necessary, simply as a marker

@implementation B
- (void)doAnotherThing
   NSLog( @"B" );

In a code like this

B *b = [B new;]
[b doSomething];

The line

   [self doAnotherThing];

in class A will lead to the execution of -doAnotherThing (B), because messages to self are late bound as every other message. The result on the console will b "B", not "A". Using self as a receiver you should not think of a single special rule. There is completely none.

(And the above example is a very good example for using self in class methods, because the same situation can occur on class methods. Using the class itself breaks polymorphism, what is one of the worst idea at all in OOP. DO use self in class methods, too.)

B. Getting self

What is self pointing to? It points to the object to whom the message is sent that caused the execution of the current method.

Having …

…[someObject doSomething]… // some object is a reference to an instance object

… as a message, a method is called, in the most simple case …

- (void)doSomething
{ … }

In such a case, self can point to an instance of the class, the method belongs to. And it can point to an instance of a subclass, the method belongs to, too. You don't know. (And this information is preserved using self to send a message as explained above.)

If the message is sent to a class object, self points to the class object, that was the receiver of the message. This is completely analogous. Therefore it is possible that self points to a subclass object:

@interface A : NSObject
+ (void)doSomething;
+ (void)doAnotherThing;

+ (void)doSomething
   [self doAntoherThing];
+ (void)doAnotherThing
   NSLog( @"A" );

@interface B : A
- (void)doSomething; // Not necessary, simply as a marker

@implementation B
+ (void)doAnotherThing
   NSLog( @"B" );

Having this classes

…[A doSomething]…

self inside -doSomething (A) points to the class object of B. Therefore [self doAnotherThing] of B(!) is executed. This is clearly different from

+ (void)doSomething
   [A doAntoherThing];

The latter version causes relevant harm to the principles of OOP.

As a side note it is possible that self inside a class method of a root class points to an instance object of the root class or any subclass. You have to keep this in mind, when writing categories on NSObject.

@Amagrammer 2009-08-21 15:49:23

Two important notes:

  1. The class itself, e.g. UIView (I'm NOT talking about a UIView object) is itself an object, and there is a self associated with it. So for example, you can reference self in a class method like this:

    // This works
    +(void) showYourself { [self performSelector: @selector(makeTheMostOfYourself)]; }
    // Class method!
    +(void) makeTheMostOfYourself { }
  2. Note that the compiler does NOT raise any warnings or errors, even if the self you mean to reference is an object and not a class. It is VERY easy to cause crashes this way, for example:

    // This will crash!
    +(void) showYourself { [self performSelector: @selector(makeTheMostOfYourself)]; }
    // Object method!
    -(void) makeTheMostOfYourself { }
    // This will crash too!
    -(void) showYourself2 { [self performSelector: @selector(makeTheMostOfYourself2)]; }
    // Class method!
    +(void) makeTheMostOfYourself2 { }

    Sadly, this makes class methods a bit harder to use, which is unfortunate because they are a valuable tool for encapsulation through information hiding. Just be careful.

@Jonathan Sterling 2010-11-24 21:26:33

If the behavior weren't like that, it would be harder to use class methods. A class is an object too, which "manages" the type of things your object can respond to. If you want to use a class method, send the message to the class. Couldn't be simpler.

@Amagrammer 2011-02-05 13:33:55

Sure. It's just a shame that the compiler can't give you a warning.

@Amin Negm-Awad 2017-10-21 00:09:53

No, it is absolutely correct to send a message to self in a class method instead of using the class itself. This is for overwriting class methods. So the compiler should give you a warning, if you use the class instead of self (or [self class]).

@Alex Rozanski 2009-08-21 11:56:29

self refers to the instance of the current class that you are working in, and yes, it is analagous to this in Java.

You use it if you want to perform an operation on the current instance of that class. For example, if you are writing an instance method on a class, and you want to call a method on that same instance to do something or retrieve some data, you would use self:

int value = [self returnSomeInteger];

This is also often used for accessor methods on an instance (i.e. setters and getters) especially with setter methods, if they implement extra functionality rather than just setting the value of an instance variable, so that you do not have to repeat that code over and over when you want to set the value of that variable, for example:

[self setSomeVariable:newValue];

One of the most common uses of self is during initialization of a class. Sample code might look like:

- (id)init
    self = [super init];

    if(self!=nil) {
        //Do stuff, such as initializing instance variables

    return self;

This invokes the superclass's (via super) initializer, which is how chained initialization occurs up the class hierarchy. The returned value is then set to self, however, because the superclass's initializer could return a different object than the superclass.

@Amin Negm-Awad 2017-10-21 00:11:11

Beside the fact, that inside a class method self is referring to a class object, not an instance object.

@iKenndac 2009-08-21 12:06:48

self is an implied argument to all Obj-C methods that contains a pointer to the current object in instance methods, and a pointer to the current class in class methods.

Another implied argument is _cmd, which is the selector that was sent to the method.

Please be aware that you only get self and _cmd in Obj-C methods. If you declare a C(++) method, for instance as a callback from some C library, you won't get self or cmd.

For more information, see the Using Hidden Arguments section of the Objective-C Runtime Programming guide.

@groundhog 2009-08-21 12:00:40

self is an object pointer to the current instances dispatch table. It is an implicit first argument to every member function of an object, and is assigned when that function is called.

In functions like init, you need to be careful that when you call the super class init you reassign self to be the return value as the super class init may redefine what self points to.

super is similar to self except it points to the superclass dispatch table.

@rpetrich 2009-08-21 14:38:00

Actually, self points to the object itself; when you call onto self, the runtime calls objc_msgSend as usual. super is different. It instructs the compiler to construct a proper objc_super struct and to call objc_msgSendSuper instead.

@Kuba Suder 2009-08-21 11:56:52

Yes, it's exactly the same as "this" in Java - it points to the "current" object.

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] What is the purpose of the word 'self'?

  • 2010-04-25 20:22:28
  • richzilla
  • 839218 View
  • 1104 Score
  • 22 Answer
  • Tags:   python class oop self

27 Answered Questions

[SOLVED] How do I sort an NSMutableArray with custom objects in it?

17 Answered Questions

[SOLVED] How do I call Objective-C code from Swift?

  • 2014-06-02 20:05:42
  • David Mulder
  • 282958 View
  • 961 Score
  • 17 Answer
  • Tags:   objective-c swift

94 Answered Questions

9 Answered Questions

[SOLVED] What does the NS prefix mean?

10 Answered Questions

[SOLVED] What is the difference between #import and #include in Objective-C?

18 Answered Questions

[SOLVED] What __init__ and self do on Python?

  • 2009-03-09 05:09:51
  • 1067763 View
  • 776 Score
  • 18 Answer
  • Tags:   python oop self

8 Answered Questions

[SOLVED] What does the "__block" keyword mean?

13 Answered Questions

[SOLVED] What is a typedef enum in Objective-C?

3 Answered Questions

[SOLVED] What does "@private" mean in Objective-C?

Sponsored Content