Objective-C Language NSString Creation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Simple:

NSString *newString = @"My String";

From multiple strings:

NSString *stringOne = @"Hello";
NSString *stringTwo = @"world";
NSString *newString = [NSString stringWithFormat:@"My message: %@ %@",
                     stringOne, stringTwo];

Using Mutable String

NSString *stringOne = @"Hello";
NSString *stringTwo = @"World";
NSMutableString *mutableString = [NSMutableString new];
[mutableString appendString:stringOne];
[mutableString appendString:stringTwo];

From NSData:

When initializing from NSData, an explicit encoding must be provided as NSString is not able to guess how characters are represented in the raw data stream. The most common encoding nowadays is UTF-8, which is even a requirement for certain data like JSON.

Avoid using +[NSString stringWithUTF8String:] since it expects an explicitly NULL-terminated C-string, which -[NSData bytes] does not provide.

NSString *newString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];

From NSArray:

NSArray *myArray = [NSArray arrayWithObjects:@"Apple", @"Banana", @"Strawberry", @"Kiwi", nil];
NSString *newString = [myArray componentsJoinedByString:@" "];


Got any Objective-C Language Question?