Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>obj-&gt;foo</code> syntax accesses the ivar <code>foo</code> of <code>obj</code> whereas <code>obj.foo</code> accesses the property (defined by <code>@property</code>). The main difference is that <code>obj-&gt;foo</code> does not use any getters/setters and writes to the ivar directly.</p> <p>For example, if you defined the property like this</p> <pre><code>@property (atomic, strong, readonly) SomeClass *foo; </code></pre> <p>Modern Objective-C compilers will automatically create an ivar <code>_foo</code> and the property <code>foo</code> for you (without the need of declaring the ivar and <code>@synthesize</code>ing the property.</p> <p><code>obj.foo</code> will then automatically use the <code>atomic</code> getter and will make the property <code>readonly</code> (ie no setter). Using the ivar syntax <code>obj-&gt;_foo</code>, you are reading the property non-atomically(!) and you can even write it (remember, the property is <code>readonly</code>!).</p> <p>Usually it's very easy: Always use the property syntax, except in <code>init</code> and <code>dealloc</code>, there you use the ivar syntax. Obviously when you are actually implementing a getter or a setter yourself, that's another place to use the ivar syntax. (thanks to @godel9). (Remember: That's a rough guideline, there are other use-cases where you might want direct ivar access).</p> <p><em>EDIT</em>: Because of some critique in the comments: It's true that the dot syntax can also be used without declaring something as <code>@property</code>, eg some use <code>array.count</code> instead of <code>[array count]</code> (for <code>NSArray *array</code>). But given that the OP asked about properties vs ivars, that was certainly not asked. Also note that for a given <code>@property ... SomeClass *foo</code> the ivar is not necessarily <code>_foo</code> but that's would be the auto-generated ivar name in recent ObjC compilers (with <code>@synthesize</code> you can map properties to arbitrary ivars).</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