With SELF or without SELF?


#1

Hi, I am learning iOS Programming with your book (3rd edition) and I have several questions.

  1. for example I have @property … circleColor and @synthesize circleColor… then in your book
    you use

which, without any modification just do this code

- (void)setCircleColor:(UIColor *)clr { circleColor = clr; } in other words: it just assings given value to circleColor property,
so what’s the difference if I call that code like this?

and then just use my circleColor property?

  1. in this line

what if I call that method with

when we really need to use SELF and why it’s so important?

Thank you for your answer and your great book!


#2

Your questions relate to some fundamental concepts and especially the distinction between setting the value of a property directly and setting it indirectly, which is covered in the Objective-C Programming Book.

Directly:

Indirectly, by invoking a method:

In your example, you are invoking the setter method setCircleColor:

[quote][code]

  • (void)setCircleColor:(UIColor *)clr
    {
    circleColor = clr;
    }
    [/code][/quote]
    If you wanted to do other things beside changing the color of the circle, then you can code accordingly inside the setter method:
- (void)setCircleColor:(UIColor *)clr
{
    circleColor = clr;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"My Circle Color has changed" object:self];
}

Now whenever you invoke this method to change the color of the circle, the method not only changes the color but also sends out a notification automatically.

[self setCircleColor:[UIColor redColor]];
[self setCircleColor:[UIColor greenColor]];
[self setCircleColor:[UIColor blueColor]];

But if you change the color directly, then you will also need to manually send out the notification:

circleColor = [UIColor redColor];
[[NSNotificationCenter defaultCenter] postNotificationName:@"My Circle Color has changed" object:self];
circleColor = [UIColor greenColor];
[[NSNotificationCenter defaultCenter] postNotificationName:@"My Circle Color has changed" object:self];
circleColor = [UIColor blueColor];
[[NSNotificationCenter defaultCenter] postNotificationName:@"My Circle Color has changed" object:self];

As for the keyword self, it always appears inside a method and refers to the object on which the method is invoked. A method is always invoked on an object; if a method that is invoked on an object wants to invoke another method on the same object then it needs a way of referring to that object, and the keyword self makes this possible.


#3

Thanks for explanation!