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