length and NSString?

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

  1. zmttoxics macrumors 65816


    May 20, 2008
    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.

    @interface count : NSObject {
    	//input box
    	IBOutlet NSTextField *textInput;
    	//output label
    	IBOutlet NSTextField *textOutput;
    - (IBAction)count:(id)sender;
    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?

  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    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.

  3. TomM macrumors newbie

    Dec 6, 2007
    The code:

    Following is code which shows the typecasting:

    - (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

    This works ok.

  4. zmttoxics thread starter macrumors 65816


    May 20, 2008
    Ah, thanks guys!

    I got it the way I wanted with:
    [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