Objective-C:如何防止抽象泄漏
我认为在 Objective-C 中,我必须将实例变量声明为类接口的一部分,即使这些变量是实现细节并且具有私有访问权限。
在“主观”C 中,我可以在 .c 文件中声明一个变量,并且它在该编译单元之外不可见。我可以在相应的 .h 文件中声明它,然后任何链接到该编译单元的人都可以看到该变量。
我想知道 Objective-C 中是否有等效的选择,或者我是否必须在 .h 中为我的类声明每个 ivar。
阿里。
I gather that in Objective-C I must declare instance variables as part of the interface of my class even if these variables are implementation details and have private access.
In "subjective" C, I can declare a variable in my .c file and it is not visible outside of that compilation unit. I can declare it in the corresponding .h file, and then anyone who links in that compilation unit can see the variable.
I wonder if there is an equivalent choice in Objective-C, or if I must indeed declare every ivar in the .h for my class.
Ari.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Ari,
关于如何完成“不可见”实例变量声明的一个很好的参考可以请在此找到,谨此致谢马特·加拉格尔 (Matt Gallagher)。
希望有帮助,
坦率
Ari,
A good reference to how to accomplish "invisible" instance variable declarations can be found here with credit respectfully given to Matt Gallagher.
Hope it helps,
Frank
传统上需要实例变量来确定类的大小。直接访问 ivars 一直是不好的做法,但这不是重点。在现代运行时,这是不太必要的,但无论如何,这不是抽象泄漏,除非客户端依赖于类的 ivars,这应该是不可能的,因为您将它们声明为
@protected
或@private
,对吧?The instance variables have traditionally been needed to determine the size of the class. It's always been poor practice to directly access the ivars, and that isn't the point. In the modern runtime, this is less necessary, but at any rate, it isn't an abstraction leak unless clients are relying on the class's ivars, which should be impossible since you're declaring them as
@protected
or@private
, right?要限制访问,您可以使用
@private
或@protected
关键字:编辑: 刮掉所有内容,事实证明我真的需要一些睡觉。
To restrict access, you can use the
@private
or@protected
keywords:EDIT: Scratch everything, turns out I really need some sleep.
默认情况下,ivars 是
@protected
(尽管@private
和@protected
不能保证其他类无法访问它们——您可以始终使用getValue:forKey:
访问 ivars)。在任何情况下,您都不应该直接从其他类直接访问 ivars——“选择”是是否将 ivars 公开为属性(您只需依赖遵循约定的所有类,不直接访问 ivars)。在新的 Objective-C 运行时中,您根本不必声明 ivars,因为它们可以在运行时合成,但不幸的是,这不适用于 iPhone 模拟器,因此目前最好只声明所有.h 文件中的 ivars。
ivars are
@protected
by default (although@private
and@protected
don't guarantee that other classes can't access them--you can always access ivars withgetValue:forKey:
). You should never directly access ivars from other classes directly in any case--the "choice" is whether or not to expose the ivars as properties (you just have to rely on all classes following the convention to not access ivars directly).In the new objective-c runtime, you don't have to declare ivars at all, since they can be synthesized at runtime, but unfortunately that doesn't work with the iPhone simulator, so for now, it's best just to declare all the ivars in the .h file.