Objective-c – Helper functions in Cocoa


What is the standard way of incorporating helper/utility functions in Obj-C classes?

I.e. General purpose functions which are used throughout the application and called by more than 1 class.

Can an Obj-C method exist outside of a class, or does it need to be a C function for it to have this kind of behaviour?

Best Solution

I would group similar functions as static methods in a helper class. These can then be called using the classname rather the instance name. Static methods are defined with a + instead of the usual -.

like so:

@interface HelperClass: superclassname {
    // instance variables - none if all methods are static.

+ (void) helperMethod: (int) parameter_varName;


This would be called like so.

[HelperClass helperMethod: 10 ];

As this is static you do not init/alloc the class. This has the advantage of clearly grouping like Helper functions. You could use standalone C functions but as your Application gets larger it can become a right mess! Hope this helps.