Operating in a text field

Discussion in 'iOS Programming' started by Programmer, Sep 28, 2009.

  1. Programmer macrumors member

    Programmer

    Joined:
    Jun 16, 2009
    #1
    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.
     
  2. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    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.
     
  3. PatrickCocoa macrumors 6502a

    Joined:
    Dec 2, 2008
    #3
    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.
     
  4. newlearner macrumors member

    newlearner

    Joined:
    Jul 30, 2009
    Location:
    india
    #4
    for the documentation you can also go to the Apple Developer Connection Cocoa. Just enter your class name in the search bar and get the relevant information

    Searching via Xcode's Help can prove cumbersome at times :)
     

Share This Page