Xcode – String concatenation
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]; myLabel.text=result;
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.
| Print article | This entry was posted by Radu Poenaru on 6 June 2009 at 2:42 pm, and is filed under CSCW Lab- iPhone. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

about 2 years ago
Man great work,ur all posts are really nice.Keep it Up.
best regards,
Abid Mehmood
about 2 years ago
a little help to undestand string concatenation:
NSString *stringOne =@”primera fila “;
NSString *stringTwo =@”segunda fila “;
NSString *stringThree =[NSString stringWithFormat:@"%@%@",stringOne,stringTwo];