length and NSString?

Discussion in 'Mac Programming' started by zmttoxics, Aug 11, 2008.

  1. macrumors 65816

    zmttoxics

    Joined:
    May 20, 2008
    #1
    I am still learning Cocoa and Objective-C. I am trying to do an exorcise in the book I have (Cocoa Programming for Mac OS X 3rd Ed. By: Aaron Hillegass), and I can't figure it out.

    I am supposed to make an application with an input text feild, a label, and a button. It's supposed to set the label the length of the text in the input box when you hit the button. I believe I have the app laid out correctly. However, I am not sure how to use the length method of the NSString class.

    Code:
    @interface count : NSObject {
    	//input box
    	IBOutlet NSTextField *textInput;
    	//output label
    	IBOutlet NSTextField *textOutput;
    }
    - (IBAction)count:(id)sender;
    @end
    
    The buttons and such are linked (as far as I can tell, if there is something you want me to check I can). But how can I set the output label to length of the input textfield?

    Thanks!
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    NSString instances respond to -length which returns an int. There is also an initializer for NSString -initWithFormat that takes an NSString format string, say, @"%d", and a variable argument list, in this case one int. Now you have an NSString with the representation of your length.

    Brought to you by the NSString class reference. I'd link it, but the iPhone has no copy-paste.

    -Lee
     
  3. macrumors newbie

    Joined:
    Dec 6, 2007
    #3
    The code:

    Following is code which shows the typecasting:

    <code>
    - (IBAction)count:(id)sender
    {
    int numLtrs;

    numLtrs = [[textField1 stringValue] length];
    NSString *string = [NSString stringWithFormat:
    @"%@ has %i letters.", [textField1 stringValue], numLtrs];

    [textField2 setStringValue: string];
    //[string release]; <-- Releasing string here causes an error
    }
    </code>

    This works ok.

    TomM
     
  4. thread starter macrumors 65816

    zmttoxics

    Joined:
    May 20, 2008
    #4
    Ah, thanks guys!

    I got it the way I wanted with:
    Code:
    [textOutput setIntValue:[[textInput stringValue] length]];
    I am a very hardcore C programmer, and though I do a lot of C++ and java, this Object-C is giving me troubles with this method calls and interface linking.

    Thanks for the help, I am sure I will be back! :D
     

Share This Page