In Objective-C, if I have a class that contains only class methods (no member variables or instance methods) can I define class methods in the class’s header file (.h), and skip creating a .m file?
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.
You can, but you basically shouldn’t. While you can put your @implementation in a header, it’s counter-convention and it may have unintended side-effects, the same as in C++ or other languages (e.g. you can’t control what will have been #included before your header was #include, so you can’t be sure you have a sane global namespace).
The best practices in Objective-C are to keep only declarations in header files, along with documentation. Since the documentation is generally quite verbose (if written well) that’s already a fair bit of content in your header – adding code on top of that would be too much.
Keep in mind also that there’s no inlining of Objective-C methods, whether class or instance. That’s one of the big reasons putting code in header files is a relatively popular practice in C/C++. You can of course put static functions in your Objective-C header file, so you could implement your code that way, but that may be an undesirable design – for example, class methods provide a form of namespacing which is generally wise to take advantage of.