When is it advisable to stop using self when accessing instance variables?

This might be a really stupid beginner question, BUT:

If you have any good instance variables in your class like UIScrollview * scrollView2 then why should you bypass the getter and setter by discarding

[self.scrollView2 addSubview:imageView];

      

and rather do

[scrollView2 addSubview:imageView]; 

      

? I mean ... it doesn't hurt to iterate over the getter, and actually I thought there was always a way. But in all of Apple's examples, I've missed this pattern all over the place. They rarely use self.someInstanceVariable when calling methods. Or have I misunderstood something?

I started to do the same as the apple, but I would like to know: why?

0


a source to share


3 answers


It has to do with KVO (Key Value Observing) and KVC ( Keyed Encoding) . If you bypass a getter or setter, objects looking at this value will not receive the message.



+3


a source


I worked around the getter / setter too, until I realized that the bindings don't work when accessing the variable directly. In other words, encoding a key value only works when accessing a property with getter / setter functions.



EDIT: See this page for KVC compliance.

+2


a source


Typically, you would not use properties in, init

or dealloc

it is best to access instance variables directly, as your object may not be in a "safe" state.

+1


a source







All Articles