1

I'm new to Objective-C.

[deskCalc add: 55]; NSLog(@"After adding %f to accumulator, accumulator is :%f", 55, [deskCalc accumulator]);

Some context; this is a snippet from a simple calculator program that looks fairly similar to the one found in the first post in this thread. As its name suggests, the add method add's the argument to an integer variable "accumulator", which stores the final value. Finally, the accumulator method simply returns the variable.

My question is: Rather than having to manually type the argument (55 in this case) after the string, is it possible to have code that references whichever argument is passed on to the add method (dynamically)?

I've seen other questions (such as this and this) that at least sound somewhat simlar to a noob like myself, but I haven't been able to join the dots and figure out a solution.

Community
  • 1
  • 1
playforest
  • 113
  • 7

1 Answers1

2

In general, you can't retrieve the argument from a previous message send expression.

One simple solution is to put the value in a variable and refer to it in both places:

float addend = 55;
[deskCalc add: addend];
NSLog(@"After adding %f to accumulator, accumulator is :%f", addend, [deskCalc accumulator]);

IF the deskCalc object were specifically coded to keep track of the last operation and its operands, you could ask it for the value. Here I hypothesize the existence of a lastAddend property on the class and use that:

[deskCalc add: 55];
NSLog(@"After adding %f to accumulator, accumulator is :%f", [deskCalc lastAddend], [deskCalc accumulator]);
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • That makes sense. Unfortunately my reputation isn't high enough yet to up-vote your response, but thank you for the quick reply Ken! Really appreciate it. – playforest Apr 19 '15 at 05:19