为什么在编译期间属性需要显式类型? [英] Why do properties require explicit typing during compilation?

查看:53
本文介绍了为什么在编译期间属性需要显式类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用属性语法进行编译需要在编译时知道接收器的类型.我可能不明白什么,但考虑到 Objective-C 是一种动态语言,这似乎是一个破碎或不完整的编译器实现.

Compilation using property syntax requires the type of the receiver to be known at compile time. I may not understand something, but this seems like a broken or incomplete compiler implementation considering that Objective-C is a dynamic language.

属性comment"定义为:

The property "comment" is defined with:

@property (nonatomic, retain) NSString *comment;

并合成:

@synthesize comment;

"document" 是符合以下条件的几个类之一的实例:

"document" is an instance of one of several classes which conform to:

@protocol DocumentComment <NSObject>

@property (nonatomic, retain) NSString *comment;

@end

并简单地声明为:

id document;

使用以下属性语法时:

stringObject = document.comment;    

gcc 产生以下错误:

the following error is generated by gcc:

error: request for member 'comment' in something not a structure or union

但是,以下等效的接收器方法语法在编译时不会发出警告或错误,并且在运行时按预期正常工作:

However, the following equivalent receiver-method syntax, compiles without warning or error and works fine, as expected, at run-time:

stringObject = [document comment];  

我不明白为什么属性需要在编译时知道接收器的类型.有什么我想念的吗?我只是使用后一种语法来避免在接收对象具有动态类型的情况下出现错误.属性似乎是半生不熟.

I don't understand why properties require the type of the receiver to be known at compile time. Is there something I am missing? I simply use the latter syntax to avoid the error in situations where the receiving object has a dynamic type. Properties seem half-baked.

推荐答案

编译属性访问需要知道如何将属性名称转换为正确的 getter/setter 名称.在不知道接收者的类型的情况下,编译器不可能知道 getter/setter 被调用的是什么,因为属性可能已经覆盖了名称作为其声明的一部分,如下所示:

Compiling property access requires knowing how to translate the property name into the correct getter/setter name. Without knowing the type of the receiver, the compiler cannot possibly know what the getter/setter is called, as the property may have overridden the name as part of its declaration, like so:

@property (nonatomic, retain, getter=myComment) NSString *comment;

如果编译器继续为您的无类型示例生成代码,它将生成 [document comment],这将在运行时失败,因为正确生成的代码实际上是 [documentmyComment].

If the compiler were to go ahead and generate code for your untyped example, it would generate [document comment], which will fail at runtime as the correct generated code is actually [document myComment].

这篇关于为什么在编译期间属性需要显式类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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