Note that there are some explanatory texts on larger screens.

plurals
  1. POMixing C pre/post increment/decrement with Objective-C dot operator works?
    primarykey
    data
    text
    <p>Say I have a class with a scalar property type:</p> <pre><code>@property (nonatomic, assign) int myInt; </code></pre> <p>And for clarity, synthesized like:</p> <pre><code>@synthesize myInt = _myInt; </code></pre> <p>If someone had asked me if the following line would work:</p> <pre><code>self.myInt++; </code></pre> <p>I would have said "No". The rationale being that we all know that the dot operator is just syntactic sugar for calling a compiler-generated getter method. So that line is literally:</p> <pre><code>[self myInt]++; </code></pre> <p>If you type that second line into Xcode, it won't compile, stating: "Assigning to 'readonly' return result of an objective-c message not allowed". This makes perfect sense, and it's what I would have expected. Even if that compiled, I would have expected the outcome to increment a copy of the backing ivar on the stack, not the ivar itself.</p> <p>But, the instruction <code>self.myInt++</code> does compile, and it works. It works just as if that dot operator were directly accessing _myInt. By supplying my own getters and setters, I can see that both the getter and the setter are used in the process, in that order, like it was actually:</p> <pre><code>[self setMyInt:[self myInt] + 1]; </code></pre> <p>So, is this an exception to the rule that the dot operator is exactly the same as a method call, or are the <code>{--, ++, +=, -=}</code> operators given special attention by the Objective-C compiler when used with dot notation? I've always thought of them as a C language features with no special considerations for Objective-C. I could see that simple line being very confusing to someone unfamiliar with Objective-C dot notation.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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