将 C 前/后递增/递减与 Objective-C 点运算符混合可以工作吗?

发布于 2024-12-12 09:16:16 字数 871 浏览 0 评论 0原文

假设我有一个具有标量属性类型的类:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苦妄 2024-12-19 09:16:16

您可以查看汇编器输出,发现它生成了两个 _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 for a = a + 1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文