将C前后的增减与Objective-C点运算符混合使用? [英] Mixing C pre/post increment/decrement with Objective-C dot operator works?

查看:89
本文介绍了将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++;

我会说不".理由是大家都知道点运算符只是调用编译器生成的getter方法的语法糖.所以这行字面意思是:

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]++;

如果您在Xcode中键入第二行,它将不会编译,并指出:不允许分配给Objective-c消息的'readonly'返回结果".这是很合理的,这就是我所期望的.即使编译完成,我也希望结果会增加堆栈中支持ivar的副本,而不是ivar本身.

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.

但是,指令self.myInt++确实可以编译,并且可以工作.就像该点运算符正在直接访问_myInt一样.通过提供自己的getter和setter,我可以看到在过程中按顺序使用了getter和setter,就像实际上是这样:

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];

那么,这是点运算符与方法调用完全相同的规则的例外吗,还是{--, ++, +=, -=}运算符与点表示法一起使用时,Objective-C编译器是否给予了特别注意?我一直将它们视为C语言功能,而对Objective-C则没有特殊考虑.我可以看到,这条简单的行对于不熟悉Objective-C点表示法的人来说非常令人困惑.

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.

推荐答案

您可以查看汇编器输出,并看到它生成了两个_objc_msgSend调用.

You can look at the assembler output and see that it generates two _objc_msgSend calls.

我想更多的情况是应用a++a = a + 1的语法糖的规则

I'd guess it's more a case of applying the rule that a++ is syntactic sugar for a = a + 1

这篇关于将C前后的增减与Objective-C点运算符混合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆