Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to self in Objective-C

I'm from the C++ world so the notion of assigning this makes me shudder:

this = new Object; // Gah! 

But in Objective-C there is a similar keyword, self, for which this is perfectly acceptable:

self = [super init]; // wait, what? 

A lot of sample Objective-C code uses the above line in init routines. My questions:

1) Why does assignment to self make sense (answers like "because the language allows it" don't count)

2) What happens if I don't assign self in my init routine? Am I putting my instance in some kind of jeopardy?

3) When the following if statement fails, what does it mean and what should I do to recover from it:

- (id) init {     self = [super init];      if (self)     {         self.my_foo = 42;     }      return self; } 
like image 811
fbrereto Avatar asked Aug 27 '09 15:08

fbrereto


People also ask

What is self in Objective C?

self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling.

Why self super init?

Why do we assign [super init] to self here? The textbook reason is because [super init] is permitted to do one of three things: Return its own receiver (the self pointer doesn't change) with inherited instance values initialized. Return a different object with inherited instance values initialized.


1 Answers

This is a topic that is frequently challenged by newcomers:

  • Wil Shipley: self = [stupid init];
  • Matt Gallagher: What does it mean when you assign [super init] to self?
  • Apple documentation: Implementing Initializers
  • Cocoa-Dev: self = [super init] debate

Basically, it stems from the idea that a superclass may have over-ridden the designated initializer to return a different object than the one returned from +alloc. If you didn't assign the return value of super's initializer into self, then you could potentially be dealing with a partially initialized object (because the object that super initialized isn't the same object that you're initializing).

On the whole, it's pretty rare for super to return something different, but it does happen in a couple of cases.

like image 190
Dave DeLong Avatar answered Oct 11 '22 14:10

Dave DeLong