将 C 前/后递增/递减与 Objective-C 点运算符混合可以工作吗?
假设我有一个具有标量属性类型的类:
@property (nonatomic, assign) int myInt;
为了清楚起见,综合如下:
@synthesize myInt = _myInt;
如果有人问我以下行是否有效:
self.myInt++;
我会说“不”。理由是我们都知道点运算符只是调用编译器生成的 getter 方法的语法糖。所以这行字面意思是:
[self myInt]++;
如果你在 Xcode 中输入第二行,它不会编译,并指出:“不允许分配给‘readonly’返回 Objective-C 消息的结果”。这是完全有道理的,这也是我所期望的。即使编译成功,我也期望结果会增加堆栈上支持 ivar 的副本,而不是 ivar 本身。
但是,指令 self.myInt++
确实可以编译,并且可以工作。它的工作原理就像点运算符直接访问 _myInt 一样。通过提供我自己的 getter 和 setter,我可以看到 getter 和 setter 都在该过程中按顺序使用,就像实际情况一样:
[self setMyInt:[self myInt] + 1];
那么,这是点运算符完全相同的规则的例外吗作为方法调用,或者与点表示法一起使用时,{--, ++, +=, -=}
运算符是否受到 Objective-C 编译器的特别关注?我一直认为它们是 C 语言的特性,对 Objective-C 没有特殊的考虑。我发现对于不熟悉 Objective-C 点表示法的人来说,这条简单的线非常令人困惑。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以查看汇编器输出,发现它生成了两个
_objc_msgSend
调用。我猜这更多是应用
a++
是a = a + 1
的语法糖这一规则的情况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 fora = a + 1