Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I use properties or direct reference when accessing instance variables internally?
    text
    copied!<p>Say I have a class like this:</p> <pre><code>@interface MyAwesomeClass : NSObject { @private NSString *thing1; NSString *thing2; } @property (retain) NSString *thing1; @property (retain) NSString *thing2; @end @implementation MyAwesomeClass @synthesize thing1, thing1; @end </code></pre> <p>When accessing <code>thing1</code> and <code>thing2</code> <em>internally</em> (i.e, within the implementation of <code>MyAwesomeClass</code>), is it better to use the property, or just reference the instance variable directly (assuming cases in which we do not do any work in a "custom" access or mutator, i.e., we just set and get the variable). Pre-Objective C 2.0, we usually just access the ivars directly, but what's the usual coding style/best practice now? And does this recommendation change if an instance variable/property is private and not accessible outside of the class at all? Should you create a property for every ivar, even if they're private, or only for public-facing data? What if my app doesn't use key-value coding features (since KVC only fires for property access)?</p> <p>I'm interested in looking beyond the low-level technical details. For example, given (sub-optimal) code like:</p> <pre><code>@interface MyAwesomeClass : NSObject { id myObj; } @proprety id myObj; @end @implementation MyAwesomeClass @synthesize myObj; @end </code></pre> <p>I know that <code>myObj = anotherObject</code> is functionally the same as <code>self.myObj = anotherObj</code>.</p> <p>But properties aren't merely fancy syntax for instructing the compiler to write accessors and mutators for you, of course; they're also a way to better encapsulate data, i.e., you can change the internal implementation of the class without rewriting classes that rely on those properties. I'm interested in answers that address the importance of this encapsulation issue when dealing with the class's own <em>internal</em> code. Furthermore, properly-written properties can fire KVC notifications, but direct ivar access won't; does this matter if my app isn't utilizing KVC features <em>now</em>, just in case it <em>might</em> in the future?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload