Say I have a class with a scalar property type:
@property (nonatomic, assign) int myInt;
And for clarity, synthesized like:
@synthesize myInt = _myInt;
If someone had asked me if the following line would work:
self.myInt++;
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:
[self myInt]++;
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.
But, the instruction self.myInt++
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:
[self setMyInt:[self myInt] + 1];
So, is this an exception to the rule that the dot operator is exactly the same as a method call, or are the {--, ++, +=, -=}
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.
Pre-increment and Post-increment concept in C/C++? Decrement operator decrease the value by one. Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.
Preincrement and Postincrement in C are the two ways to use the increment operator. In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable.
Pre increment directly returns the incremented value, but post increments need to copy the value in a temporary variable, increment the original and then returns the previous made copy.
In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1. Simple enough till now. However, there is an important difference when these two operators are used as a prefix and a postfix.
You can look at the assembler output and see that it generates two _objc_msgSend
calls.
I'd guess it's more a case of applying the rule that a++
is syntactic sugar for a = a + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With