Self keyword


#1

Hi everyone!
I know, my question might be a bit silly, but I can’t still get the idea of the ‘self’ usage.
For example, here is the implementation of addAssetsObject: method in “Employee.m”

- (void)addAssetsObject:(Asset *)a
{
     if (!assets) 
     {
          assets = [[NSMutableArray alloc] init];
     }
     [assets addObject:a];
     [a setHolder:self];
}

I understand that the last line must assign an Employee object as a holder of an Asset object. But according to Mr. Hillegass ‘self’ keyword definition, ‘self’ is a pointer to the object that is running the method. But setHolder: is the method of an Asset class. So shouldn’t ‘self’ in the last line assign an Asset object as a holder of an Asset object (while a is a pointer to an Asset object). It doesn’t make sense to me.
I’d be grateful if you could find a spare moment to explain this to me.
Thanks in advance,
Zakk Vald


#2

Note in Employee.m that addAssetsObject: is a method on the Employee class.

This means that all references to ‘self’ in that method will point to an Employee object: the object “running the method”.

In the book’s example, ‘setHolder’ is a synthesized method, but it can be helpful to look at an unsynthesized way of setting ‘holder’ which would be something like this:

- (void)setHolder:(Employee *)e
{
     holder = e;
}

When that Employee pointer (called ‘self’ over in the Employee’s addAssetsObject: method) gets handed over to the Asset’s setHolder: method, the pointer is then referred to as ‘e’ within that method. Inside the setHolder: method, any reference to something called ‘self’ would be an Asset object, and you can know this because setHolder: is a method of the Asset class.

I try to mentally convert this line of code like this comment:


#3

oh my… thank you a LOT! You have to write a book on Obj-C! Really, you’ve got the talent :wink: