instance variables in @interface; header vs implementation

℡╲_俬逩灬. 提交于 2019-12-09 14:45:59

问题


Is there any difference between declaring a private instance variable in the header vs declaring it in the implementation?

in TestObj.h

@interface TestObj : NSObject
{
    int test;
}
@end

vs in TestObj.m

@interface TestObj()
{
    int test;
}
@end

Both seem equivalent to me, is there any actual difference between declaring an instance variable in the header vs in the implementation, if not which is preferred? The @interface within the implementation file just seems like a way to declare private properties, does it have any other purpose outside that?


回答1:


The preference is generally to place private instance variables and properties in the private class extension (in the .m) and leave the public interface file (.h) for those properties and methods that are truly part of the public interface.

It helps isolate implementation details from the public interface and makes everything much cleaner. It also ensures that external classes do not inadvertently alter the private variables of this class.

See Class Extensions Extend the Internal Implementation.




回答2:


Greg Parker's comment on the accepted answer is the best answer here:

There is one functional difference: ivars in the class's @interface are @protected by default, and ivars in a class extension @interface or in @implementation are @private by default.



来源:https://stackoverflow.com/questions/18616709/instance-variables-in-interface-header-vs-implementation

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