firstresponder
firstresponder

Reputation: 5100

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?

Upvotes: 20

Views: 11291

Answers (3)

Peter Hosey
Peter Hosey

Reputation: 96323

I don't see why people are avoiding creating functions. Objective-C is a superset of C, which means that C is part of it. Moreover, it's completely integrated—there's no wall between them.

Create functions! It's fine! Foundation does it. Application Kit does it. Core Animation does it. Core Media does it.

I see no reason not to.

Upvotes: 20

AnthonyLambert
AnthonyLambert

Reputation: 8830

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;

@end

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.

Tony

Upvotes: 27

Jason Coco
Jason Coco

Reputation: 78343

There are a number of options for this in Objective-C. First, since Obj-C is a strict superset of C, you can define all your library functions in a separate module (source file) and happily call them from any Obj-C object/code you already have. If you create an obj-c source file (.m file) you can then call back into/use objects.

If your generic functions are logically manipulating other, established objects (for instances, operates on an NSString), you can use categories to graph your functions on already existing classes (where that makes sense).

Finally, as Tony points out, you can create classes with static methods (although I like this option the least, personally). I tend to use a mix of one an two... adding categories where appropriate and using standard functions for others. I generally only make a new class where it makes sense to design a class.

Upvotes: 7

Related Questions