Search code examples
objective-cterminologyliteralsobjective-c-literals

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' 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'.


Solution

  • 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).