(Objective C) Should methods and variables be declared in the head (.h) file if it is used only in its own class?

I went through many code examples and found that people usually declare all methods and globals in a header file (.h). It's necessary?

+3


source to share


3 answers


Methods that should be used publicly (for example, for classes other than the class that implements the method) and (truly) global variables should indeed be declared in the header file. The point is that you can import the header file into another source code file to access the functionality declared there.

Methods that must be private, that must be called as part of the internal implementation of a class, can be declared in the class extension . In recent versions of LLVM / Xcode, you don't even need to do this for non @property methods. You can simply implement them and the compiler will be smart enough to see that they exist when called from other methods in the same class implementation.



If you need to explicitly define a private ivar (rare these days), you can do so in the bracketed section right after @implementation

or @interface ClassName ()

.

In short: declare methods, functions and variables that must be accessible from other classes in the .h file. Private methods and variables should be kept private by declaring them only in the .m file.

+10


source


In the latest versions of the SDK, you don't need to declare methods that you only use inside the class so that you can dump the clutter in your .h file. In general, the only methods, properties and ivars that I have nested in my .h are the ones I know of other classes. This way, I am never wrong about external access to property that should only be internal. For the rest, I added the class extension to the .m file as follows:



#import "MyClass.h"

@interface MyClass ()
{
    int _myIvar; // I rarely use these anymore,
                 // but if you want to use them, they go here.
}

@property (strong, nonatomic) NSArray *someArray;
@property (strong, nonatomic) NSDictionary *anotherProperty

@end

@implementation MyClass

@end

      

+4


source


Header files have no special meaning to the compiler. The preprocessor just copies them into the implementation file when you write #import anyway.

0


source







All Articles