views:

122

answers:

4

I'm trying to put buttons that have operators on them, like / * +, etc. I want to store the operator in such a way that I can use it in an expression, like 1 var 2 = 8

I would like to avoid having to use a different method for each operator, so an operator var would be my best option, I think. Objective-C for iPhone

A: 

There's no such thing in C. You'll have to use a selector which invokes a method to do what you want.

JeremyP
+3  A: 

The usual OO way to do this is to create a class "mathOperator" that has a method "performOp" taking two parameters, then inherit different classes from it that represent the different operations. I'm not an expert in objective-C, so my syntax is probably a bit off, but I think you'd write something like:

result = [var On:arg1 And:arg2];

for example

result = [var On:2 And:3];

would set result to 5 or 6 depending on whether var was set to add or mul. The implementation would look like (again, very roughly):

@interface Add: mathOperator
-(int)On: (int)arg1 And: (int)arg2;
@end

...

@implementation Add
-(int)On:  (int)arg1 And: (int)arg2 {
    return arg1 + arg2;
}

and of course similar for the other operators:

@implementation Mul
-(int)On:  (int)arg1 And: (int)arg2 {
    return arg1 * arg2;
}
psmears
+4  A: 

Read ch 5 in Cocoa Design Patterns. The approach used is to define "Command" classes that will perform each operation defined as a class method "execute". Then you can dynamically perform the operation by obtaining the appropriate class by using the following

commandName = [NSString stringWithFormat:@"MY%@Command", [commandString capitalizedString]];
commandClass = NSClassFromString(commandName);  
result = [commandClass executeWithXValue:x yValue:y]; 
falconcreek
+1  A: 

The way i'd do it is to make methods for each type of arithmatic and pass the numbers into them. Then instead of all that with the variable call the function.

lindasvalle