Confusion with simple NString manipulation in Objective C

Coming from a Java background, I’ve found it extremely difficuilt to do any simple String manipulation.

My first attempt was

NSString *string1  = @"This is a";
NSString *string2 = @" test";
NSString *newString = string1 + string2;

As it turns out this doesn’t work so well. After much frustration I found the following solution

NSString *string1  = @"This is a";
NSString *string2 = @" test";
NSString *newString = [string1 stringByAppendingString:string2];

A couple of other useful manipulations are the sub string manipulators

NSString *newString2 = [string1 substringToIndex:4];
NSString *newString3 = [string1 substringFromIndex:4];

Which using the Strings from above give “This” and ” is a” respectively.

Posted on July 22, 2009 at 2:02 pm by Alastair Munro · Permalink
In: Iphone · Tagged with: ,

Leave a Reply