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
1
vote
1 answer

Command in Xcode to rewrite array creation to use literal syntax

I watched a WWDC video and saw that there is a Refactor option in Xcode that -- boom -- can automatically update your whole code to use the new, more readable notation. Rather than doing [NSArray arrayWithObjects @"a",@"b",@"c",nil], e.g. , you…
user4951
  • 32,206
  • 53
  • 172
  • 282
0
votes
1 answer

Xcode Project can not find .framework classes to import

I am working on a project, that reads the bank cards. The card reader company provided a .framework SDK but does not provide any technical support. I search on Google and find out how to add .framework into the project. I followed the following…
0
votes
1 answer

Objective-C: What's the difference between @[ ] and [[NSArray alloc] initWithCapacity:0]

I have a method to build and return an array: - (NSArray *)foo { NSUInteger capacity = [self getArrayCapacity]; if (capacity == 0) { return @[]; } else { NSMutableArray *array = [[NSMutableArray alloc]…
0
votes
0 answers

Creating an NSDictionary by writing values inside curly braces

The NSDictionary class allows me to initialise it like this: NSDictionary* attributes = @{ NSFontAttributeName: font }; What is this construction method called, and how I can implement it in my own class? I want to have a class with properties…
Rudolfs Bundulis
  • 11,636
  • 6
  • 33
  • 71
0
votes
1 answer

Safe Subscripting of NSDictionary

With literals syntax one can use NSDictionary *dictionary like this to get the objectForKey NSDictionary * dictionary; id object = dictionary[key]; But if the type of dictionary is of type id and you try to write id dictionary; id object =…
hariszaman
  • 8,202
  • 2
  • 40
  • 59
0
votes
1 answer

Edit entry in NSMutableDictionary fails with error: "unrecognized selector sent to instance"

I have a NSMutableDictionary that is initialized like this: dictionary = [NSMutableDictionary dictionaryWithDictionary:@{ @"0": @{ @"title": @"Description", @"value": @"Enter Description", }, @"1": @{ @"title":…
0
votes
2 answers

Storing new objects of various datatypes in an NSDictionary

The Realm migration example on the Realm documentation site shows an example with a new NSString object. The example is simple and well explained. if (oldSchemaVersion < 2) { newObject[@"email"] = @""; // creates an NSString object... } But…
iKK
  • 6,394
  • 10
  • 58
  • 131
0
votes
3 answers

objective-c JSON literals, nested - most elegant solution?

Say you do this, NSString *teste = yourData[@"title"]; no problem if "title" is completely missing in the json: you just get null. If you do this: NSString *teste = yourData[@"location"][@"city"]; if "city" is missing in the json nest, no problem.…
Fattie
  • 27,874
  • 70
  • 431
  • 719
0
votes
1 answer

What is the meaning of @[object1, object2]?

Possible Duplicate: What kind of object does @[obj1, obj2] create? Looking at the Master-Detail Template in Xcode, in the App Delegate the SplitViewController's view controllers are set like so: self.splitViewController.viewControllers =…
Infinity James
  • 4,667
  • 5
  • 23
  • 36
1 2 3
4