How to concatenate strings (i.e. print several at a time)

- by

This is really simple in PHP, however it’s not obvious in Objective-C because you’re not printing the strings directly. Rather you print two objects that point to each string. There is a method though which has the same effect: stringByAppendingString. Here’s how you use it:

self.myLabel.text = [@"This is " stringByAppendingString: @"my label"];

It gets a bit more complex when you want to add three or more together; each stringByAppendingString expression needs to be in [brackets] before you add another one, like so:

self.myLabel.text = [[@"This is " stringByAppendingString: @"my label "] 
    stringByAppendingString @"which is rather complex"];

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

1 thought on “How to concatenate strings (i.e. print several at a time)”

  1. If you just want to print several strings that don’t necessarily have to become a single new string you can also choose to print them like this:

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

    The %@ will be replaced with nameString. You can add as many as you like.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.