ObjectiveCLiterals.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. ====================
  2. Objective-C Literals
  3. ====================
  4. Introduction
  5. ============
  6. Three new features were introduced into clang at the same time:
  7. *NSNumber Literals* provide a syntax for creating ``NSNumber`` from
  8. scalar literal expressions; *Collection Literals* provide a short-hand
  9. for creating arrays and dictionaries; *Object Subscripting* provides a
  10. way to use subscripting with Objective-C objects. Users of Apple
  11. compiler releases can use these features starting with the Apple LLVM
  12. Compiler 4.0. Users of open-source LLVM.org compiler releases can use
  13. these features starting with clang v3.1.
  14. These language additions simplify common Objective-C programming
  15. patterns, make programs more concise, and improve the safety of
  16. container creation.
  17. This document describes how the features are implemented in clang, and
  18. how to use them in your own programs.
  19. NSNumber Literals
  20. =================
  21. The framework class ``NSNumber`` is used to wrap scalar values inside
  22. objects: signed and unsigned integers (``char``, ``short``, ``int``,
  23. ``long``, ``long long``), floating point numbers (``float``,
  24. ``double``), and boolean values (``BOOL``, C++ ``bool``). Scalar values
  25. wrapped in objects are also known as *boxed* values.
  26. In Objective-C, any character, numeric or boolean literal prefixed with
  27. the ``'@'`` character will evaluate to a pointer to an ``NSNumber``
  28. object initialized with that value. C's type suffixes may be used to
  29. control the size of numeric literals.
  30. Examples
  31. --------
  32. The following program illustrates the rules for ``NSNumber`` literals:
  33. .. code-block:: objc
  34. void main(int argc, const char *argv[]) {
  35. // character literals.
  36. NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z']
  37. // integral literals.
  38. NSNumber *fortyTwo = @42; // equivalent to [NSNumber numberWithInt:42]
  39. NSNumber *fortyTwoUnsigned = @42U; // equivalent to [NSNumber numberWithUnsignedInt:42U]
  40. NSNumber *fortyTwoLong = @42L; // equivalent to [NSNumber numberWithLong:42L]
  41. NSNumber *fortyTwoLongLong = @42LL; // equivalent to [NSNumber numberWithLongLong:42LL]
  42. // floating point literals.
  43. NSNumber *piFloat = @3.141592654F; // equivalent to [NSNumber numberWithFloat:3.141592654F]
  44. NSNumber *piDouble = @3.1415926535; // equivalent to [NSNumber numberWithDouble:3.1415926535]
  45. // BOOL literals.
  46. NSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES]
  47. NSNumber *noNumber = @NO; // equivalent to [NSNumber numberWithBool:NO]
  48. #ifdef __cplusplus
  49. NSNumber *trueNumber = @true; // equivalent to [NSNumber numberWithBool:(BOOL)true]
  50. NSNumber *falseNumber = @false; // equivalent to [NSNumber numberWithBool:(BOOL)false]
  51. #endif
  52. }
  53. Discussion
  54. ----------
  55. NSNumber literals only support literal scalar values after the ``'@'``.
  56. Consequently, ``@INT_MAX`` works, but ``@INT_MIN`` does not, because
  57. they are defined like this:
  58. .. code-block:: objc
  59. #define INT_MAX 2147483647 /* max value for an int */
  60. #define INT_MIN (-2147483647-1) /* min value for an int */
  61. The definition of ``INT_MIN`` is not a simple literal, but a
  62. parenthesized expression. Parenthesized expressions are supported using
  63. the `boxed expression <#objc_boxed_expressions>`_ syntax, which is
  64. described in the next section.
  65. Because ``NSNumber`` does not currently support wrapping ``long double``
  66. values, the use of a ``long double NSNumber`` literal (e.g.
  67. ``@123.23L``) will be rejected by the compiler.
  68. Previously, the ``BOOL`` type was simply a typedef for ``signed char``,
  69. and ``YES`` and ``NO`` were macros that expand to ``(BOOL)1`` and
  70. ``(BOOL)0`` respectively. To support ``@YES`` and ``@NO`` expressions,
  71. these macros are now defined using new language keywords in
  72. ``<objc/objc.h>``:
  73. .. code-block:: objc
  74. #if __has_feature(objc_bool)
  75. #define YES __objc_yes
  76. #define NO __objc_no
  77. #else
  78. #define YES ((BOOL)1)
  79. #define NO ((BOOL)0)
  80. #endif
  81. The compiler implicitly converts ``__objc_yes`` and ``__objc_no`` to
  82. ``(BOOL)1`` and ``(BOOL)0``. The keywords are used to disambiguate
  83. ``BOOL`` and integer literals.
  84. Objective-C++ also supports ``@true`` and ``@false`` expressions, which
  85. are equivalent to ``@YES`` and ``@NO``.
  86. Boxed Expressions
  87. =================
  88. Objective-C provides a new syntax for boxing C expressions:
  89. .. code-block:: objc
  90. @( <expression> )
  91. Expressions of scalar (numeric, enumerated, BOOL), C string pointer
  92. and some C structures (via NSValue) are supported:
  93. .. code-block:: objc
  94. // numbers.
  95. NSNumber *smallestInt = @(-INT_MAX - 1); // [NSNumber numberWithInt:(-INT_MAX - 1)]
  96. NSNumber *piOverTwo = @(M_PI / 2); // [NSNumber numberWithDouble:(M_PI / 2)]
  97. // enumerated types.
  98. typedef enum { Red, Green, Blue } Color;
  99. NSNumber *favoriteColor = @(Green); // [NSNumber numberWithInt:((int)Green)]
  100. // strings.
  101. NSString *path = @(getenv("PATH")); // [NSString stringWithUTF8String:(getenv("PATH"))]
  102. NSArray *pathComponents = [path componentsSeparatedByString:@":"];
  103. // structs.
  104. NSValue *center = @(view.center); // Point p = view.center;
  105. // [NSValue valueWithBytes:&p objCType:@encode(Point)];
  106. NSValue *frame = @(view.frame); // Rect r = view.frame;
  107. // [NSValue valueWithBytes:&r objCType:@encode(Rect)];
  108. Boxed Enums
  109. -----------
  110. Cocoa frameworks frequently define constant values using *enums.*
  111. Although enum values are integral, they may not be used directly as
  112. boxed literals (this avoids conflicts with future ``'@'``-prefixed
  113. Objective-C keywords). Instead, an enum value must be placed inside a
  114. boxed expression. The following example demonstrates configuring an
  115. ``AVAudioRecorder`` using a dictionary that contains a boxed enumeration
  116. value:
  117. .. code-block:: objc
  118. enum {
  119. AVAudioQualityMin = 0,
  120. AVAudioQualityLow = 0x20,
  121. AVAudioQualityMedium = 0x40,
  122. AVAudioQualityHigh = 0x60,
  123. AVAudioQualityMax = 0x7F
  124. };
  125. - (AVAudioRecorder *)recordToFile:(NSURL *)fileURL {
  126. NSDictionary *settings = @{ AVEncoderAudioQualityKey : @(AVAudioQualityMax) };
  127. return [[AVAudioRecorder alloc] initWithURL:fileURL settings:settings error:NULL];
  128. }
  129. The expression ``@(AVAudioQualityMax)`` converts ``AVAudioQualityMax``
  130. to an integer type, and boxes the value accordingly. If the enum has a
  131. :ref:`fixed underlying type <objc-fixed-enum>` as in:
  132. .. code-block:: objc
  133. typedef enum : unsigned char { Red, Green, Blue } Color;
  134. NSNumber *red = @(Red), *green = @(Green), *blue = @(Blue); // => [NSNumber numberWithUnsignedChar:]
  135. then the fixed underlying type will be used to select the correct
  136. ``NSNumber`` creation method.
  137. Boxing a value of enum type will result in a ``NSNumber`` pointer with a
  138. creation method according to the underlying type of the enum, which can
  139. be a :ref:`fixed underlying type <objc-fixed-enum>`
  140. or a compiler-defined integer type capable of representing the values of
  141. all the members of the enumeration:
  142. .. code-block:: objc
  143. typedef enum : unsigned char { Red, Green, Blue } Color;
  144. Color col = Red;
  145. NSNumber *nsCol = @(col); // => [NSNumber numberWithUnsignedChar:]
  146. Boxed C Strings
  147. ---------------
  148. A C string literal prefixed by the ``'@'`` token denotes an ``NSString``
  149. literal in the same way a numeric literal prefixed by the ``'@'`` token
  150. denotes an ``NSNumber`` literal. When the type of the parenthesized
  151. expression is ``(char *)`` or ``(const char *)``, the result of the
  152. boxed expression is a pointer to an ``NSString`` object containing
  153. equivalent character data, which is assumed to be '\\0'-terminated and
  154. UTF-8 encoded. The following example converts C-style command line
  155. arguments into ``NSString`` objects.
  156. .. code-block:: objc
  157. // Partition command line arguments into positional and option arguments.
  158. NSMutableArray *args = [NSMutableArray new];
  159. NSMutableDictionary *options = [NSMutableDictionary new];
  160. while (--argc) {
  161. const char *arg = *++argv;
  162. if (strncmp(arg, "--", 2) == 0) {
  163. options[@(arg + 2)] = @(*++argv); // --key value
  164. } else {
  165. [args addObject:@(arg)]; // positional argument
  166. }
  167. }
  168. As with all C pointers, character pointer expressions can involve
  169. arbitrary pointer arithmetic, therefore programmers must ensure that the
  170. character data is valid. Passing ``NULL`` as the character pointer will
  171. raise an exception at runtime. When possible, the compiler will reject
  172. ``NULL`` character pointers used in boxed expressions.
  173. Boxed C Structures
  174. ------------------
  175. Boxed expressions support construction of NSValue objects.
  176. It said that C structures can be used, the only requirement is:
  177. structure should be marked with ``objc_boxable`` attribute.
  178. To support older version of frameworks and/or third-party libraries
  179. you may need to add the attribute via ``typedef``.
  180. .. code-block:: objc
  181. struct __attribute__((objc_boxable)) Point {
  182. // ...
  183. };
  184. typedef struct __attribute__((objc_boxable)) _Size {
  185. // ...
  186. } Size;
  187. typedef struct _Rect {
  188. // ...
  189. } Rect;
  190. struct Point p;
  191. NSValue *point = @(p); // ok
  192. Size s;
  193. NSValue *size = @(s); // ok
  194. Rect r;
  195. NSValue *bad_rect = @(r); // error
  196. typedef struct __attribute__((objc_boxable)) _Rect Rect;
  197. NSValue *good_rect = @(r); // ok
  198. Container Literals
  199. ==================
  200. Objective-C now supports a new expression syntax for creating immutable
  201. array and dictionary container objects.
  202. Examples
  203. --------
  204. Immutable array expression:
  205. .. code-block:: objc
  206. NSArray *array = @[ @"Hello", NSApp, [NSNumber numberWithInt:42] ];
  207. This creates an ``NSArray`` with 3 elements. The comma-separated
  208. sub-expressions of an array literal can be any Objective-C object
  209. pointer typed expression.
  210. Immutable dictionary expression:
  211. .. code-block:: objc
  212. NSDictionary *dictionary = @{
  213. @"name" : NSUserName(),
  214. @"date" : [NSDate date],
  215. @"processInfo" : [NSProcessInfo processInfo]
  216. };
  217. This creates an ``NSDictionary`` with 3 key/value pairs. Value
  218. sub-expressions of a dictionary literal must be Objective-C object
  219. pointer typed, as in array literals. Key sub-expressions must be of an
  220. Objective-C object pointer type that implements the
  221. ``<NSCopying>`` protocol.
  222. Discussion
  223. ----------
  224. Neither keys nor values can have the value ``nil`` in containers. If the
  225. compiler can prove that a key or value is ``nil`` at compile time, then
  226. a warning will be emitted. Otherwise, a runtime error will occur.
  227. Using array and dictionary literals is safer than the variadic creation
  228. forms commonly in use today. Array literal expressions expand to calls
  229. to ``+[NSArray arrayWithObjects:count:]``, which validates that all
  230. objects are non-``nil``. The variadic form,
  231. ``+[NSArray arrayWithObjects:]`` uses ``nil`` as an argument list
  232. terminator, which can lead to malformed array objects. Dictionary
  233. literals are similarly created with
  234. ``+[NSDictionary dictionaryWithObjects:forKeys:count:]`` which validates
  235. all objects and keys, unlike
  236. ``+[NSDictionary dictionaryWithObjectsAndKeys:]`` which also uses a
  237. ``nil`` parameter as an argument list terminator.
  238. Object Subscripting
  239. ===================
  240. Objective-C object pointer values can now be used with C's subscripting
  241. operator.
  242. Examples
  243. --------
  244. The following code demonstrates the use of object subscripting syntax
  245. with ``NSMutableArray`` and ``NSMutableDictionary`` objects:
  246. .. code-block:: objc
  247. NSMutableArray *array = ...;
  248. NSUInteger idx = ...;
  249. id newObject = ...;
  250. id oldObject = array[idx];
  251. array[idx] = newObject; // replace oldObject with newObject
  252. NSMutableDictionary *dictionary = ...;
  253. NSString *key = ...;
  254. oldObject = dictionary[key];
  255. dictionary[key] = newObject; // replace oldObject with newObject
  256. The next section explains how subscripting expressions map to accessor
  257. methods.
  258. Subscripting Methods
  259. --------------------
  260. Objective-C supports two kinds of subscript expressions: *array-style*
  261. subscript expressions use integer typed subscripts; *dictionary-style*
  262. subscript expressions use Objective-C object pointer typed subscripts.
  263. Each type of subscript expression is mapped to a message send using a
  264. predefined selector. The advantage of this design is flexibility: class
  265. designers are free to introduce subscripting by declaring methods or by
  266. adopting protocols. Moreover, because the method names are selected by
  267. the type of the subscript, an object can be subscripted using both array
  268. and dictionary styles.
  269. Array-Style Subscripting
  270. ^^^^^^^^^^^^^^^^^^^^^^^^
  271. When the subscript operand has an integral type, the expression is
  272. rewritten to use one of two different selectors, depending on whether
  273. the element is being read or written. When an expression reads an
  274. element using an integral index, as in the following example:
  275. .. code-block:: objc
  276. NSUInteger idx = ...;
  277. id value = object[idx];
  278. it is translated into a call to ``objectAtIndexedSubscript:``
  279. .. code-block:: objc
  280. id value = [object objectAtIndexedSubscript:idx];
  281. When an expression writes an element using an integral index:
  282. .. code-block:: objc
  283. object[idx] = newValue;
  284. it is translated to a call to ``setObject:atIndexedSubscript:``
  285. .. code-block:: objc
  286. [object setObject:newValue atIndexedSubscript:idx];
  287. These message sends are then type-checked and performed just like
  288. explicit message sends. The method used for objectAtIndexedSubscript:
  289. must be declared with an argument of integral type and a return value of
  290. some Objective-C object pointer type. The method used for
  291. setObject:atIndexedSubscript: must be declared with its first argument
  292. having some Objective-C pointer type and its second argument having
  293. integral type.
  294. The meaning of indexes is left up to the declaring class. The compiler
  295. will coerce the index to the appropriate argument type of the method it
  296. uses for type-checking. For an instance of ``NSArray``, reading an
  297. element using an index outside the range ``[0, array.count)`` will raise
  298. an exception. For an instance of ``NSMutableArray``, assigning to an
  299. element using an index within this range will replace that element, but
  300. assigning to an element using an index outside this range will raise an
  301. exception; no syntax is provided for inserting, appending, or removing
  302. elements for mutable arrays.
  303. A class need not declare both methods in order to take advantage of this
  304. language feature. For example, the class ``NSArray`` declares only
  305. ``objectAtIndexedSubscript:``, so that assignments to elements will fail
  306. to type-check; moreover, its subclass ``NSMutableArray`` declares
  307. ``setObject:atIndexedSubscript:``.
  308. Dictionary-Style Subscripting
  309. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  310. When the subscript operand has an Objective-C object pointer type, the
  311. expression is rewritten to use one of two different selectors, depending
  312. on whether the element is being read from or written to. When an
  313. expression reads an element using an Objective-C object pointer
  314. subscript operand, as in the following example:
  315. .. code-block:: objc
  316. id key = ...;
  317. id value = object[key];
  318. it is translated into a call to the ``objectForKeyedSubscript:`` method:
  319. .. code-block:: objc
  320. id value = [object objectForKeyedSubscript:key];
  321. When an expression writes an element using an Objective-C object pointer
  322. subscript:
  323. .. code-block:: objc
  324. object[key] = newValue;
  325. it is translated to a call to ``setObject:forKeyedSubscript:``
  326. .. code-block:: objc
  327. [object setObject:newValue forKeyedSubscript:key];
  328. The behavior of ``setObject:forKeyedSubscript:`` is class-specific; but
  329. in general it should replace an existing value if one is already
  330. associated with a key, otherwise it should add a new value for the key.
  331. No syntax is provided for removing elements from mutable dictionaries.
  332. Discussion
  333. ----------
  334. An Objective-C subscript expression occurs when the base operand of the
  335. C subscript operator has an Objective-C object pointer type. Since this
  336. potentially collides with pointer arithmetic on the value, these
  337. expressions are only supported under the modern Objective-C runtime,
  338. which categorically forbids such arithmetic.
  339. Currently, only subscripts of integral or Objective-C object pointer
  340. type are supported. In C++, a class type can be used if it has a single
  341. conversion function to an integral or Objective-C pointer type, in which
  342. case that conversion is applied and analysis continues as appropriate.
  343. Otherwise, the expression is ill-formed.
  344. An Objective-C object subscript expression is always an l-value. If the
  345. expression appears on the left-hand side of a simple assignment operator
  346. (=), the element is written as described below. If the expression
  347. appears on the left-hand side of a compound assignment operator (e.g.
  348. +=), the program is ill-formed, because the result of reading an element
  349. is always an Objective-C object pointer and no binary operators are
  350. legal on such pointers. If the expression appears in any other position,
  351. the element is read as described below. It is an error to take the
  352. address of a subscript expression, or (in C++) to bind a reference to
  353. it.
  354. Programs can use object subscripting with Objective-C object pointers of
  355. type ``id``. Normal dynamic message send rules apply; the compiler must
  356. see *some* declaration of the subscripting methods, and will pick the
  357. declaration seen first.
  358. Caveats
  359. =======
  360. Objects created using the literal or boxed expression syntax are not
  361. guaranteed to be uniqued by the runtime, but nor are they guaranteed to
  362. be newly-allocated. As such, the result of performing direct comparisons
  363. against the location of an object literal (using ``==``, ``!=``, ``<``,
  364. ``<=``, ``>``, or ``>=``) is not well-defined. This is usually a simple
  365. mistake in code that intended to call the ``isEqual:`` method (or the
  366. ``compare:`` method).
  367. This caveat applies to compile-time string literals as well.
  368. Historically, string literals (using the ``@"..."`` syntax) have been
  369. uniqued across translation units during linking. This is an
  370. implementation detail of the compiler and should not be relied upon. If
  371. you are using such code, please use global string constants instead
  372. (``NSString * const MyConst = @"..."``) or use ``isEqual:``.
  373. Grammar Additions
  374. =================
  375. To support the new syntax described above, the Objective-C
  376. ``@``-expression grammar has the following new productions:
  377. ::
  378. objc-at-expression : '@' (string-literal | encode-literal | selector-literal | protocol-literal | object-literal)
  379. ;
  380. object-literal : ('+' | '-')? numeric-constant
  381. | character-constant
  382. | boolean-constant
  383. | array-literal
  384. | dictionary-literal
  385. ;
  386. boolean-constant : '__objc_yes' | '__objc_no' | 'true' | 'false' /* boolean keywords. */
  387. ;
  388. array-literal : '[' assignment-expression-list ']'
  389. ;
  390. assignment-expression-list : assignment-expression (',' assignment-expression-list)?
  391. | /* empty */
  392. ;
  393. dictionary-literal : '{' key-value-list '}'
  394. ;
  395. key-value-list : key-value-pair (',' key-value-list)?
  396. | /* empty */
  397. ;
  398. key-value-pair : assignment-expression ':' assignment-expression
  399. ;
  400. Note: ``@true`` and ``@false`` are only supported in Objective-C++.
  401. Availability Checks
  402. ===================
  403. Programs test for the new features by using clang's \_\_has\_feature
  404. checks. Here are examples of their use:
  405. .. code-block:: objc
  406. #if __has_feature(objc_array_literals)
  407. // new way.
  408. NSArray *elements = @[ @"H", @"He", @"O", @"C" ];
  409. #else
  410. // old way (equivalent).
  411. id objects[] = { @"H", @"He", @"O", @"C" };
  412. NSArray *elements = [NSArray arrayWithObjects:objects count:4];
  413. #endif
  414. #if __has_feature(objc_dictionary_literals)
  415. // new way.
  416. NSDictionary *masses = @{ @"H" : @1.0078, @"He" : @4.0026, @"O" : @15.9990, @"C" : @12.0096 };
  417. #else
  418. // old way (equivalent).
  419. id keys[] = { @"H", @"He", @"O", @"C" };
  420. id values[] = { [NSNumber numberWithDouble:1.0078], [NSNumber numberWithDouble:4.0026],
  421. [NSNumber numberWithDouble:15.9990], [NSNumber numberWithDouble:12.0096] };
  422. NSDictionary *masses = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:4];
  423. #endif
  424. #if __has_feature(objc_subscripting)
  425. NSUInteger i, count = elements.count;
  426. for (i = 0; i < count; ++i) {
  427. NSString *element = elements[i];
  428. NSNumber *mass = masses[element];
  429. NSLog(@"the mass of %@ is %@", element, mass);
  430. }
  431. #else
  432. NSUInteger i, count = [elements count];
  433. for (i = 0; i < count; ++i) {
  434. NSString *element = [elements objectAtIndex:i];
  435. NSNumber *mass = [masses objectForKey:element];
  436. NSLog(@"the mass of %@ is %@", element, mass);
  437. }
  438. #endif
  439. #if __has_attribute(objc_boxable)
  440. typedef struct __attribute__((objc_boxable)) _Rect Rect;
  441. #endif
  442. #if __has_feature(objc_boxed_nsvalue_expressions)
  443. CABasicAnimation animation = [CABasicAnimation animationWithKeyPath:@"position"];
  444. animation.fromValue = @(layer.position);
  445. animation.toValue = @(newPosition);
  446. [layer addAnimation:animation forKey:@"move"];
  447. #else
  448. CABasicAnimation animation = [CABasicAnimation animationWithKeyPath:@"position"];
  449. animation.fromValue = [NSValue valueWithCGPoint:layer.position];
  450. animation.toValue = [NSValue valueWithCGPoint:newPosition];
  451. [layer addAnimation:animation forKey:@"move"];
  452. #endif
  453. Code can use also ``__has_feature(objc_bool)`` to check for the
  454. availability of numeric literals support. This checks for the new
  455. ``__objc_yes / __objc_no`` keywords, which enable the use of
  456. ``@YES / @NO`` literals.
  457. To check whether boxed expressions are supported, use
  458. ``__has_feature(objc_boxed_expressions)`` feature macro.