Questions tagged [objective-c-literals]

Clang 3.1 and Apple's LLVM 4.0 introduced new literal syntax for object creation and collection indexing in Objective-C, allowing simpler use of NSNumber, NSArray and NSDictionary. Use this tag for questions regarding that syntax.

Objective-C has always had compiler support for creation of object instances from literal character strings, just as C allows creation of a char * from a literal string. In Cocoa programming (and other frameworks that derive from or imitate NeXTSTEP'S frameworks), the construct @"Lemon curry?" in source code creates an NSString instance.

Clang 3.1 and Apple's LLVM 4.0 compiler introduced support for other literal objects, expanding the use of the @ character to denote object creation from what would otherwise appear to be primitives. The new syntax allows creation of NSNumbers, NSArrays, and NSDictionarys, as well as "boxing" of scalar expressions (such as enums and BOOLs).

For (contrived) example,

@[ @{ @3 : @(NSCaseInsensitiveSearch) }, @{ @"With a melon?" : @(YES) } ];

creates an NSArray containing two NSDictionarys, the first of which has a key/value pair of an NSNumber whose value is 3 and an NSNumber whose value is the numerical value of NSCaseInsensitiveSearch. The second dictionary has a pair whose key is a string and whose value is a boxed BOOL, which also becomes an NSNumber object.

Previous to the introduction of this syntax, the creation of these objects would have been much more unwieldy:

[NSArray arrayWithObjects:[NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedInteger:NSCaseInsensitiveSearch]
                                                      forKey:[NSNumber numberWithInt:3]],
                          [NSDictionary dictionaryWithObject:@"With a melon?"
                                                      forKey:[NSNumber numberWithBool:YES]], nil];

There is an important distinction, although an implementation detail, between literal strings and this new literal support. @"Lemon curry" is an instance of __NSCFConstantString, a private subclass of NSString, which is created at compile-time, and whose contents are stored in the DATA segment of the program's binary. By contrast, the literal syntax for other objects is rewritten by the compiler into constructor method calls -- these objects are created at runtime, just as any other instance of their classes would be. (For this reason, literals other than NSStrings cannot be used to initialize a static or global variable.)

Associated indexing syntax for dictionaries and arrays was also added. Starting from the array created above,

NSDictionary * d = theArray[1];
NSNumber * n = d[@"With a melon?"];

results in n holding an NSNumber representing the boolean value YES. It should be noted that this indexing feature requires framework support which is not present in SDKs pre-iOS 6 or OS X 10.8. (The compiler does not rewrite the subscript operation into objectAtIndex: and objectForKey:, but objectAtIndexedSubscript:, and objectForKeyedSubscript: which do not exist in earlier versions of Foundation.)

Such support can be added fairly easily, however. See Is there any way to get the neat Objective-C literal indexing feature in Xcode 4.4? or Aaron Hayman's answer to Compiler error "expected method not found" when using subscript on NSArray

Full details of this syntax can be found at the Clang website: https://clang.llvm.org/docs/ObjectiveCLiterals.html

54 questions
191
votes
4 answers

What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?

I was going through the release notes for Xcode 4.4 and noticed this: LLVM 4.0 Compiler Xcode now includes the Apple LLVM Compiler version 4.0, including the following newObjective-C language features: [...] - Objective-C literals: create…
Pedro Mancheno
  • 5,237
  • 4
  • 24
  • 31
57
votes
5 answers

Is there a literal syntax for mutable collections?

I know I can create an NSArray with @[@"foo", @"bar"] or an NSDictionary with @{@0 : @"foo", @1 : @"bar"}. Is there a literal syntax for creating an NSMutableArray or an NSMutableDictionary?
53
votes
2 answers

Is there some literal dictionary or array syntax in Objective-C?

It's always been possible to create NSArrays (and NSDictionaries/NSNumber) with vararg method calls, like: [NSArray arrayWithObjects: @"a", @"b", @"c", nil]; Can these be created with in-line literals in a new improvement to LLVM and Clang?
AlBlue
  • 23,254
  • 14
  • 71
  • 91
33
votes
7 answers

Compiler error "expected method not found" when using subscript on NSArray

I wrote this simple code to try out the new Objective-C literal syntax for NSArrays: NSArray *array = @[@"foo"]; NSLog(@"%@", array[0]); The first line works fine, but the subscripting results in an error: Expected method to read array element…
29
votes
3 answers

What is the difference between @YES/@NO and YES/NO?

In Objective-c what is the difference between @YES/@NO and YES/NO? What types are used for each?
cdub
  • 24,555
  • 57
  • 174
  • 303
20
votes
4 answers

@"" string type literals for NSNumber

I love the shorthand handling of string literals in Objective C with the @"string" notation. Is there any way to get similar behavior with NSNumbers? I deal with numbers more and it's so tedious having [NSNumber numberWithWhatever:] calls…
rob5408
  • 2,972
  • 2
  • 40
  • 53
19
votes
2 answers

Can the new Clang Objective-C literals be redirected to custom classes?

Although the overloading of @ begins to tread on dangerous territory, I love the addition of the new Objective-C literals in Clang 3.1. Unfortunately the new literals are of limited use to me. Except for instances where code needs to interface with…
Rabbit
  • 566
  • 5
  • 13
16
votes
2 answers

Indenting Objective-C literals with Xcode

Xcode think that this: NSArray *persons = @[ @{ @"name": @"Bob", @"pet": @"cat" }, @{ @"name": @"Alice", @"pet": @"dog" } ]; would be better indented like so: NSArray *persons = @[ @{ @"name":…
Tyilo
  • 28,998
  • 40
  • 113
  • 198
13
votes
3 answers

iOS: "attempt to insert nil object from objects[1]" when creating dictionary

I'm creating a custom navigation bar class and customizing it's title attributes using the following code: self.titleTextAttributes = @{ UITextAttributeFont: bariol, UITextAttributeTextColor: [UIColor whiteColor] …
beakr
  • 5,709
  • 11
  • 42
  • 66
13
votes
1 answer

Creating an NSMutableArray with a literal via mutableCopy or arrayWithArray:

Possible Duplicate: Is literal creation of an NSMutableDictionary less efficient than the class helper method? According to the WWDC video that introduces ObjectiveC literals, NSMutableArrays can be initialized like so: [NSMutableArray…
KDaker
  • 5,899
  • 5
  • 31
  • 44
12
votes
2 answers

Using @[array, of, items] vs [NSArray arrayWithObjects:]

Is there a difference between NSArray *myArray = @[objectOne, objectTwo, objectThree]; and NSArray *myArray = [NSArray arrayWithObjects:objectOne, objectTwo, objectThree, nil]; Is one preferred over the other?
Bot
  • 11,868
  • 11
  • 75
  • 131
12
votes
1 answer

Is literal creation of an NSMutableDictionary less efficient than the class helper method?

Is it appreciably more efficient to create an NSMutableDictionary using a constructor [NSMutableDictionary dictionaryWithObjectsAndKeys:@"object1", @"key1", @2, @"key2", nil]; than taking the mutable copy of a literal [@{@"key1":@"object1",…
Cody C
  • 3,087
  • 4
  • 24
  • 32
10
votes
1 answer

Is the literal object syntax only available for OS X development?

Are the new Objective-C literal syntax additions (e.g. @3.14) only available when developing for OS X and not iOS? That's what the Xcode update 4.4 seems to suggest. If so, why?
hanno
  • 6,401
  • 8
  • 48
  • 80
8
votes
1 answer

Can Objective-C's new literal syntax mimic the addObject?

I know that I can do this to : NSMutableArray *objects = [@[objectOne, objectTwo] mutableCopy]; NSObject *someObject = [NSObject new]; objects[0] = someObject; But is there a way for the new literal syntax to mimic addObject:?
Matt Foley
  • 921
  • 1
  • 8
  • 24
8
votes
3 answers

Difference between @[] and [NSArray arrayWithObjects:]

Possible Duplicate: Should I prefer to use literal syntax or constructors for creating dictionaries and arrays? Is there any difference between: NSArray *array = @[@"foo", @"bar"]; and NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar",…
Almas Adilbek
  • 4,371
  • 10
  • 58
  • 97
1
2 3 4