Help with HelloWorld Objective-C
I'm Very new to Objective-C iPhone programming. I'm kinda gonna go with the trial-and-error method on this one:P. So my question has to do with getting a name. Here's my code:
-(IBActio开发者_如何学Pythonn)sayHello:(id)sender{
NSString *name = [textField text];
label.text = [NSString stringWithFormat:@"Hello ", name];
What this does is get the text from a UITextField (I already have this setup) and outputs to a UILabel. I would think this would work, but apparently not, because it just outputs "Hello ". Missing the name. Help would be appreciated :)
Thanks,
Eric
EDIT: Thanks to all that responded. It worked! :)
It should read:
label.text = [NSString stringWithFormat:@"Hello %@", name];
stringWithFormat
uses "%" sequences to insert values into the string it's building. You use different "%" sequences depending on what type of value you're inserting: "%@" is for Objective-C objects, "%d" is for integers, and so forth. You can insert multiple values by using multiple "%" sequences, for example:
label.text = [NSString stringWithFormat:@"Hello %@ %@ and your %d friends", firstName, lastName, 7];
Try this:
[NSString stringWithFormat:@"Hello %@", name];
-(IBAction)sayHello:(id)sender{
NSString *name = [textField text];
label.text = [NSString stringWithFormat:@"Hello %@", name];
}
You have to add %@
, so that it will place your name string in the formatted string.
You need a format specifier:
label.text = [NSString stringWithFormat:@"Hello %@", name];
The %@ format specifier means "an NSObject reference". For formatting other datatypes - int, double, etc. you should use %d, %f and so on.
精彩评论