Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Programmer

macrumors member
Original poster
Jun 16, 2009
79
0
How do you do simple math operations in a text field. Like in a calculator but but adds or subtracts a preset number. I tried this:

NumberDisplay.text + 2;

But it didn't work.
 
I tried this:

NumberDisplay.text + 2;

But it didn't work.
That's because NumberDisplay.text is an NSString object and the '+' operator doesn't work with it; it only works with basic data types. You'll need to do some type conversion here.

But really what I think you need to do is step away from the real coding, go (re)learn the basics of Objective-C and even object-oriented programming and only come back to the real code once you are much more comfortable with those.
 
To answer your question, here's how to switch between numbers and strings:

1. If you have a number in the variable "justAnotherNumber" and want to put it in a string "numberAsString":

int justAnotherNumber = 1; // or whatever number
NSString * numberAsString = [NSString stringWithFormat:mad:"%4d", justAnotherNumber];

2. If you have a string in the variable "numberAsString" and want to put it in a numeric variable:
int justAnotherNumber;
NSString * numberAsString = NumberDisplay.text;
justAnotherNumber = [numberAsString intValue];

Now you can add two to justAnotherNumber or do whatever else you have in mind.

====

Have fun!

Note that you can take the previous poster's advice and actually learn what you're doing before you do it. But you need some small victories along the way, so use the code above and knock yourself out.

Also, you may want to learn how to use the documentation in Xcode and look up NSString. Just read through the various methods to see what you can do to a string. That documentation is where intValue and stringWithFormat are described (along with many, many other neat things you can do).

To get to the documentation, in Xcode use the menu Help / Developer Documentation, enter NSString in the search bar, select NSString class reference on the left, then read through the text.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.