Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Method Implementation in Header

Tags:

objective-c

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?

like image 711
Mr. Smith Avatar asked Dec 09 '12 10:12

Mr. Smith


1 Answers

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.

like image 127
Wade Tregaskis Avatar answered Oct 21 '22 10:10

Wade Tregaskis