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
4
votes
3 answers

+[NSNumber numberWithUnsignedInteger:] Literal?

I know I can do @3 instead of [NSNumber numberWithInt:3] but what's the literal for [NSNumber numberWithUnsignedInteger:3]?
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
3
votes
3 answers

Objective-C at sign and curly braces, @{ ... } what does it mean?

I have this line in Objective-C. NSMutableArray *mutableArray; [mutableArray addObject:@{ @"Something" : aObject, @"Otherthing" : anotherObject }]; What does the @{ ... } part do exactly? It is an object, but it seems to create some kind of key,…
unom
  • 11,438
  • 4
  • 34
  • 54
3
votes
3 answers

Should I prefer to use literal syntax or constructors for creating dictionaries and arrays?

I am reading through the iOS Developer Guide to get familiarized with the Objective-C language and currently I am having a little confusion on the topic of Container Literals and Subscript Notation as it pertains to creating objects like…
Moose
  • 1,270
  • 2
  • 19
  • 33
2
votes
1 answer

Can't instantiate NSNumber with shorthand @n type syntax when using enum?

I have an enum defined like this: typedef enum dataTypes{ LOW, MEDIUM, HIGH, MAX_DATA_TYPE } dataTypeEnum; I'd like to be able to instantiate an NSArray of NSNumbers like so: NSArray * numsToUse = @[@LOW, @MEDIUM]; This is not…
helloB
  • 3,472
  • 10
  • 40
  • 87
2
votes
2 answers

How does PFObject allow subscripting like NSMutableDictionary?

I was reading Parse's iOS Developers Guide. I got confused where it shows PFObject assigning to keys with subscript syntax. PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"]; gameScore[@"score"] = @1337; gameScore[@"playerName"] =…
Vivart
  • 14,900
  • 6
  • 36
  • 74
2
votes
3 answers

Why are instances created using a 'literal syntax' known as 'literals'?

Something that is bothering me is why the term 'literal' is used to refer to instances of classes like NSString and NSArray. I had only seen the term used in reference to NSString and being naive I thought it had something to do with it 'literally'…
cheznead
  • 2,589
  • 7
  • 29
  • 50
2
votes
2 answers

Selector name for NSArray literal constructor, like @[]?

It's been a while since Clang added Objective-C literal syntax for NSDictionary, NSArray, NSNumber, and BOOL literals, like @[object1, object2,] or @{key : value} I'm looking for the selector name associated with the array literal, @[]. I tried to…
2
votes
3 answers

What does @[] mean?

I am looking at a tutorial and I am not sure what the line of code means: self.objectsToShare = @[URL]; URL is an NSURL, and self.objectsToShare is an NSArray.
Alan
  • 9,331
  • 14
  • 52
  • 97
2
votes
1 answer

Special way of representing array in objective-c

I have seen in many places over the net and even in apple documentation when an array is represented in the following format: @[obj1,obj2] For eg; In predicate programming guide there is a statement like this: NSCompoundPredicate *predicate =…
Rakesh
  • 3,370
  • 2
  • 23
  • 41
2
votes
3 answers

Converting property lists into Objective-C literals

I'm not sure if this is possible, but I've seen people do crazy things with regex and other tools. I want to convert this plist to an Objective-C literals: ar +54## #### ####
Snowman
  • 31,411
  • 46
  • 180
  • 303
1
vote
1 answer

Rewrite literal NSArray to compile on gcc for OS X 10.6

I got a suggestion here on SO to write this line: NSArray *files = @[url]; However my Xcode/gcc is outdated as I'm still using OSX 10.6. How do I rewrite this line so that it will compile?
Igor
  • 5,620
  • 11
  • 51
  • 103
1
vote
0 answers

Class-level objectForKeyedSubscript:

I get an error when I use objectForKeyedSubscript: as a class level method, so in my class "MyExample.h/.m" I have something like the following: + (id)objectForKeyedSubscript:(NSString*)key; and I want to do MyExample[@"key"], I initialize a…
Jimmy
  • 10,427
  • 18
  • 67
  • 122
1
vote
1 answer

Technical term for accessing an array with an index and square brackets

What is the term or name of the operation for getting member of an array? For example, this method returns a simple array: - (NSArray*)createArray { NSArray *myArray = [[NSArray alloc] initWithObjects:@"unordentliches array", @"beliebiges…
Unheilig
  • 16,196
  • 193
  • 68
  • 98
1
vote
2 answers

What does a square-bracketed index after an NSArray mean?

Going through iTunes U Developing iOS 7 Apps for iPhone and iPad and in Lecture 3 slides, on page 120, there's a Quiz question that asks what the following line of code does. Frankly, I'm a bit stumped, and hoped someone could break it…
1
vote
3 answers

Difference between literals and class methods for NSMutableArray and NSMutableDictionary

When I started with OSX/iOS I used NSMutableArray * a1 = [NSMutableArray arrayWithCapacity:123] ; NSMutableDictionary * d1 = [NSMutableDictionary dictionaryWithCapacity:123] ; Then I discovered the 'simpler' version …
verec
  • 5,224
  • 5
  • 33
  • 40