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?
I have reviewed many code samples and have found that people commonly declare all
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
@implementationor@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.