简体   繁体   中英

Get method arguments dynamically in Objective-C

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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM