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

114 Views Asked by At

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' being a string, that is between quotation markers. Sorry if that sounds pathetic, but that was how I had been thinking about it.

Then today I learned that certain instances of NSArray can also be referred to as literal instances, i.e. an instance of the class created using a 'literal syntax'.

3

There are 3 best solutions below

11
Rob Napier On BEST ANSWER

As @Linuxios notes, literal syntaxes are built into the language. They're broader than you think, though. A literal just means that an actual value is encoded in the source. So there are quite a few literal syntaxes in ObjC. For example:

  • 1 - int
  • 1.0 - double
  • 1.0f - float
  • "a" - C-string
  • @"a" - NSString
  • @[] - NSArray
  • ^{} - function

Yeah, blocks are just function literals. They are an anonymous value that is assignable to a symbol name (such as a variable or constant).

Generally speaking, literals can be stored in the text segment and be computed at compile time (rather than at run time). If I remember correctly, array literals are currently expanded into the equivalent code and evaluated at runtime, but @"..." string literals are encoded into the binary as static data (at least now they are; non-Apple versions of gcc used to encode an actual function call to construct static strings as I remember).

0
Linuxios On

A literal syntax or a literal is just an object that was created using a dedicated syntax built into the language instead of using the normal syntax for object creation (whatever that is).

Here I create a literal array:

NSArray* a = @[@"Hello", @"World"];

Which is, for all intents and purposes equivalent to this:

NSArray* a = [NSArray arrayWithObjects:@"Hello", @"World", nil];

The first is called a literal because the @[] syntax is built into the language for creating arrays, in the same way that the @"..." syntax is built in for creating NSStrings.

0
jscs On

the term 'literal' is used to refer to instances of classes

It's not referring to the instance really; after the object is created, the way it was created doesn't matter:

NSArray * thisWasCreatedWithALiteral = @[@1, @2];
NSArray * butWhoCares = thisWasCreatedWithALiteral;

The "literal" part is just the special syntax @[@1, @2], and

it ha[s] something to do with it 'literally' being a string, that is between quotation markers.

is exactly right: this is a written-out representation of the array, as opposed to one created with a constructor method like arrayWithObjects: