Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
firstresponder Avatar asked Dec 15 '08 07:12

firstresponder


People also ask

What is the function of helper?

A "helper function" is a function you write because you need that particular functionality in multiple places, and because it makes the code more readable. A good example is an average function. You'd write a function named avg or similar, that takes in a list of numbers, and returns the average value from that list.

What are helpers and why do we use them?

A helper is a person who helps another person or group with a job they are doing. The cook and her helpers provided us with refreshment.

What are helper objects?

These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job. As an example, many people have a Closer helper object. This will take various closeable objects, for example, java.

How do you call a helper function?

To call another function in the same helper, use the syntax: this. methodName , where this is a reference to the helper itself. For example, helperMethod2 calls helperMethod3 with this code. this.


2 Answers

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

like image 107
AnthonyLambert Avatar answered Oct 02 '22 17:10

AnthonyLambert


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.

like image 24
Peter Hosey Avatar answered Oct 02 '22 16:10

Peter Hosey