Xcode – String concatenation

Xcode Don’t be fooled that Objective-C is a Object oriented language. For decades operators overloading is something standard in almost all of them.

But in Objective-C you don’t have it. Mostly, I believe that comes from the struggle of Apple guys to assure the stability of the system. A lot of errors can come from poorly designed overloads, thus the crashes can appear.

Now let’s put some hands on code.

In C, Java or Pascal you would have written something like the following for string concatenation:

string1 = string2 + string3;

But in Objective-C you need to do something different:

NSString *myString = @"http://www.mywebsite.com"; 
float myValue = 4; 
NSString *result = [NSString stringWithFormat:@"%@?query=%.3f&a",myString,myValue]; 

But beware! Read the documentation regarding formats!

It is very important to use the correct String Format Specifiers:

  • %S is used for a "Null-terminated array of 16-bit Unicode characters". And %s is used for a "Null-terminated array of 8-bit unsigned characters.
  • %s interprets its input in the system encoding rather than, for example, UTF-8.". The key being that these are arrays, not objects.
  • %@: "Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise". That sounds a bit more like a NSString. It’s an Objective-C object after all.