Over recent versions there have been lots of new Objective-C literals, some I use more readily than others. However, I often forget some of the new ones and this post is as much about updating anyone who is not using them as much as it is to remind myself what each of them are.
First of all what is an “Objective-C Literal”? An Objective-C Literal is a piece of code that references a specific Cocoa object allocating the necessary memory if needed. The most commonly known and widest use literal is the @ used in front of a C-string literal to create an NSString.
NSString Literal
NSString *str = @"This is a string"; |
The newest literals are for NSNumbers, NSArrays, and NSDictionaries. The best way to show how to use each of these is simply by code snippets.
NSNumber Literal
NSNumber *fortyTwo = @42; // equivalent to NSNumber *fortyTwo = [NSNumber numberWithInt:42] |
NSArray Literal
NSArray *array = @[@"Item1", @"Item2", @"Item3"]; // equivalent to NSArray *array = [NSArray arrayWithObjects:@"Item1", @"Item2", @"Item3" nil]; |
NSDictionary Literal
NSDictionary *dictionary = @{ @"Key1" : @"Item1", @"Key2" : @"Item2", @"Key3" : @"Item3" }; // equivalent to NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Item1", @"Item2", @"Item3", nil] forKeys:[NSArray arrayWithObjects:@"Key1", @"Key2", @"Key3", nil]]; |
For more detail please look at the documentation here.