user1457161
user1457161

Reputation: 1

Objective-C - Hello World app modification

I'm just learning to do the "Hello, World" app. But I have a question. I'd like to change the code so the result reads "World, Hello" but can't figure out what I'm doing wrong.

Here's the original code:

- (IBAction)changeGreeting:(id)sender {

self.userName = self.textField.text;

NSString *nameString = self.userName;
if ([nameString length] == 0) {
    nameString = @"World";
}
    NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
    self.label.text = greeting;
}

and I thought it would work if I could change it to:

- (IBAction)changeGreeting:(id)sender {

self.userName = self.textField.text;

NSString *nameString = self.userName;
if ([nameString length] == 0) {
    nameString = @"World";
}
    NSString *greeting = [[NSString alloc] initWithFormat:nameString , @"Hello, %@!"];
    self.label.text = greeting;
}

However that still didn't work. What would I do to make that work?

Upvotes: 0

Views: 364

Answers (1)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

Change this line

NSString *greeting = [[NSString alloc] initWithFormat:nameString , @"Hello, %@!"];

To

NSString *greeting = [[NSString alloc] initWithFormat:@"%@, Hello!", nameString];

initWithFormat, uses place holder when you write @"%@, Hello!" the "%@" indicates that the following string nameString will be replaced by it So when we @"%@, Hello!" we really mean @"nameString, Hello!" (nameString in your example is World)

Upvotes: 5

Related Questions