Objective-c – “Private methods” or static functions in Objective-C. Which one should I use

cocoaobjective c

When reading Best way to define private methods for a class in Objective-C I end up with a programming style doubt. Which is the better solution (in terms of style) to this problem? To use a category and declare it in the @interface directive in the .m file or go with the static function that receives an object.

Thanks

Best Answer

If you do not have an immediate answer as to which to use, prefer functions.

I use functions most of the time (> 90%).

Methods are useful for polymorphism and the interface.

There are other considerations for each:

Functions will generally be smaller, faster, and the compiler has the ability to inline them. If there is no reason to cause a problem by using a method and you do not need to have any exclusive in-class use, then go with the function.

Methods (or categories, if you prefer) are handy if you don't want accessor overhead or want some other feature which is available in the instance method, such as @synchronized. In my programs, these features are far less likely, and there is usually no need to use methods.

Methods export additional symbols, and generally incur a higher (but small) overhead, as a result, they typically make the binary slightly larger and the executable slightly slower (not usually noticed, unless you use them often).

There is also a risk in using/creating private methods, in that receivers/subclasses may implement/declare the method. It's often an unnecessary risk. I prefer the compiler/linker to sort this out for me, rather than find out that it is hitting an odd case at runtime 2 weeks after shipping (and difficult to locate the problem). Methods may also be useful if you intend on making the interface public sometime soon.