views:

36

answers:

2

I need to calculate from pricing based on some business rules and I do not want to duplicate this across several ViewControllers. Coming from a .Net world I would use a static method on a class to do this. What is a similar solution in Objective-C?

+3  A: 

A class method most likely - ie. a function in the interface declared with a + at the start.

@implementation PriceCalculator

+ (float)calculatePrice:(float)param1 {
    return param1*4.0;
}

@end

(and a similar @interface in a header file)

which is called like so:

price = [PriceCalculator calculatePrice:3.0];
JosephH
+1  A: 

If you don't need to override the behavior in subclasses, you can just write a C function, which is the equivalent of a static method in Java and C#. Otherwise, do as JosephH suggested, and write a class method. Here's his example rewritten as a C function:

float calculatePrice(float amount)
{
    return amount * 4.0;
}

The function could be declared/implemented in the .h/.m pair of files for one of your classes if that's convenient, but you could also create a separate .h/.m pair that just contains C functions if you like.

jlehr