Objective-C: how to prevent abstraction leaks

三世轮回 提交于 2019-12-23 11:44:47

问题


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.


回答1:


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




回答2:


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?




回答3:


To restrict access, you can use the @private or @protected keywords:

@interface Foo : NSObject {
    @private
    int barPrivate;

    @protected
    int barProtected;

    @public
    int barPublic;
}
@end

EDIT: Scratch everything, turns out I really need some sleep.




回答4:


ivars are @protected by default (although @private and @protected don't guarantee that other classes can't access them--you can always access ivars with getValue: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.



来源:https://stackoverflow.com/questions/2542226/objective-c-how-to-prevent-abstraction-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!