Reputation:
I have reviewed many code samples and have found that people commonly declare all methods and global variables in the header (.h) file. Is it necessary?
Upvotes: 5
Views: 2682
Reputation: 21373
Methods to be used publicly (i.e. by classes other than the class implementing the method) and (truly) global variables should indeed be declared in the header file. The whole point is that you can import the header file in another source code file to gain access to the functionality declared there.
Methods that are meant to be private -- that is only to be called as part of the internal implementation of a class -- can be declared in a class extension. With recent versions of LLVM/Xcode, you actually don't even need to do that for non-@property methods. You can simply implement them and the compiler will be smart enough to see that they're there when called from other methods in the same class's implementation.
If you need to explicitly define a private ivar (rare these days), you can do so in a brace-enclosed section immediately after @implementation
or @interface ClassName ()
.
In short: declare methods, functions, and variables that need be accessible from other classes in the .h file. Private methods and variable should be kept private by declaring them only in the .m file.
Upvotes: 11
Reputation: 41801
Header files have no special significance at all to the compiler. The preprocessor just copy-pastes them into the implementation file when you write #import anyway.
Upvotes: 0
Reputation: 8148
In recent versions of the SDK, you don’t have to declare methods that you only use internally to the class, so that can cut down clutter in your .h file. In general, the only methods, properties, and ivars that I put in my .h are the ones that I know other classes will need access to. That way, I never make the mistake of externally accessing a property that is supposed to be internal-only. The rest, I put in a class extension in the .m file like this:
#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
Upvotes: 5