I just dived in the world of programming on the iOS platform and I have made my first Hello World app.
I want to add extra functions to the app to learn more programming in Xcode.
In short, the apps adds the input you gave in the text field @ hallo and if you insert nothing it says Hello World!. (It adds World!)
Now I want the app to recognize a certain input so if I input a certain name (Kim) it gives not the standard response “hello Kim!” but for example hello Girl!.
This is the code that adds “world!” after “hello” if you let the input empty, so I figured this is the place to add some extra code for the extra feature.
This is the code I’m talking about in the HellowWorldViewController.m
- (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;
}
This is what I came up with :
- (IBAction)changeGreeting:(id)sender {
self.userName = self.textField.text;
NSString *nameString = self.userName;
if ([nameString length] == 0) {
nameString = @"World";
}
if (String == "Kim") {
nameString = @"Girl";
}
NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
self.label.text = greeting;
}
I get two errors “Expected expression” and “Use of undeclared identifier ‘String’; did you mean ‘NSString’?
Change:
to:
You have two problems:
Stringdidn’t mean anything to your program, there is no variable or class called String. You probably just meantnameString.Strings need to be compared differently to using
==so useisEqualToStringinstead.==checks for identity. That is whether the two objects are the same object and point to the same address in memory.isEqualToby default does the same thing, but can be overridden to perform different equality comparisons.isEqualToStringis just like this, but even more explicit.This might not be the only problem with your code but it’s the most obvious one I found.
@Jim found another problem: Strings in objective-c start with an @ symbol.