为什么我们必须在Objective-C中执行[MyClass类]? [英] Why do we have to do [MyClass class] in Objective-C?
问题描述
在Objective-C中,您可以使用以下方法调用类方法:
In Objective-C, you can invoke class methods with:
[MyClass aClassMethod];
您可以使用以下方法查询实例的种类:
And you can query an instance's kind with:
[someInstance isKindOfClass:[MyClass class]];
但是,为什么我们需要做[MyClass class]
,而不是像这样简单地提供MyClass
:
But, why do we need to do [MyClass class]
, and not simply provide MyClass
like this:
[someInstance isKindOfClass:MyClass];
是否有理由让编译器可以将MyClass
作为接收方(指针类型)而不是作为参数来进行处理?解析语言是否有局限性?还是编译器的局限性?
Is there a reason that the compiler is fine with encountering MyClass
as a receiver (a pointer type) but not as an argument? Is it a limitation of parsing the language? Or perhaps a limitation of the compiler?
推荐答案
噢...好玩的问题.答案是c-ism.
Ooooh... fun question. The answer is a c-ism.
考虑:
@interface MyClass : NSObject
@end
@implementation MyClass
@end
现在,说您有:
...
MyClass *m = nil;
...
在这种情况下,编译器将MyClass
视为类型定义. *
说变量m
是pointer to a hunk o' memory that contains one (or many -- don't forget your C pointer-fu) MyClass instances
.
In that context, the compiler sees MyClass
as a type definition. The *
says that the variable m
is a pointer to a hunk o' memory that contains one (or many -- don't forget your C pointer-fu) MyClass instances
.
换句话说,MyClass
是一种类型.
In other words, MyClass
is a type.
但是,在类似这样的上下文中:
But, in the context of something like:
[someInstance isKindOfClass: x ];
x
必须是右值,或者用人类的话来说,是表达式的值.但是,类型不能用作右值.
x
must be an rvalue or, in human terms, the value of an expression. A type, however, cannot be used as an rvalue.
[MyClass class]
的工作实际上在语言和编译器上都是有点破绽,因为语法专门允许类型名称作为消息接收者(成为方法调用的目标).
That [MyClass class]
works is actually a bit of a hack, both in the language and the compiler in that the grammar specifically allows a type name to be the message receiver (to be the target of a method call).
事实上,您可以执行以下操作:
And, as a matter of fact, you can do:
typedef MyClass Foo;
....
[MyClass class];
[Foo Class];
一切正常.但是,您不能执行以下,但是错误消息会显示出来:
It'll all work. However, you can't do the following but the error message is illuminating:
[NSUInteger class];
错误:"NSUInteger"不是Objective-C类名称或别名
现在,为什么不把它作为裸名在任何地方都进行特殊处理?
Now, why not special case it everywhere as a bare name?
这会混淆类型名和右值,您很快就不得不吞下[foo isKindOfClass: (MyClass)];
之类的东西,而对[foo isKindOfClass: (MyClass *)];
进行倒刺,然后以一种相当不舒服的方式侵犯了类型转换区域.
That colludes type names and rvalues and you quickly end up having to swallow something like [foo isKindOfClass: (MyClass)];
while barfing on [foo isKindOfClass: (MyClass *)];
which then encroaches upon typecasting territory in a rather uncomfortable fashion.
这篇关于为什么我们必须在Objective-C中执行[MyClass类]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!