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

zmttoxics

macrumors 65816
Original poster
May 20, 2008
1,020
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

@implementation count
- (id)init
{
[super init];
NSLog(@"init");
return self;
}
- (IBAction)count:(id)sender
{
//This part is wrong, I know
[textOutput setStringValue:[textInput stringValue]];
NSLog(@"Counting...");
}
@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!
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
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.

-Lee
 

TomM

macrumors newbie
Dec 6, 2007
17
0
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
 

zmttoxics

macrumors 65816
Original poster
May 20, 2008
1,020
1
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.