Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I should access the instance variable directly from within an initialization method?

The Apple Programming with Objective-C document states that:

You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may very well override the behavior.

But I don't know what side effects will be in a setter method, please give me a example to explain why I have to access the instance variable directly from within an initialization method

like image 728
NOrder Avatar asked Jul 17 '13 14:07

NOrder


2 Answers

The answer is simple - it is code smell. Dot notation like self.foobar = something in Objective-C is just a syntactic sugar for messaging. Sending messages to self is normally fine. But there are two cases you need to avoid them:

1. When the object is being created, and

2. When the object is being destroyed.

At these two times, the object is in a strange in-between state. It lacks integrity. Calling methods during these times is a code smell because every method should maintain invariants as it operates on the object.

like image 149
Oleksandr Karaberov Avatar answered Sep 28 '22 04:09

Oleksandr Karaberov


If a setter method is overridden by a subclass, you have no guarantee that your instance variable will contain the correct data. If you want to maintain data integrity within your objects during a crucial phase such as initialization, you should do as Apple recommends.

like image 23
Jacob Relkin Avatar answered Sep 28 '22 04:09

Jacob Relkin