Expression Literals
Expression literals, also known as boxed expressions, enable you to create literals from parentheses-enclosed expressions. The syntax of an expression literal is
@( <expression> )
The expression evaluates to either a scalar (numeric, enumerations, BOOL) or C-string pointer type. The type of the resultant object corresponds to the type of the expression. Scalar types produceNSNumber instances and C strings produce NSString objects using UTF-8 character encoding. The following statement creates an NSNumber instance using a boxed expression.
NSNumber *degrees2Radians = @( M_PI / 180.0 );
In the preceding example, the arithmetic expression M_PI/180.0 is evaluated and the result is boxed; that is, it is used to create an NSNumber instance. The equivalent statement for this boxed expression is
NSNumber *degrees2Radians = [NSNumber numberWithDouble:(M_PI / 180.0)];
The next example creates an NSString instance using a boxed expression.
NSString *currentUser = @(getenv("USER"));
The getenv() function retrieves the value of an environment variable, where the input parameter is the name of the variable to be retrieved. The return value to the function is a pointer to a C string.
Although enumerations are typically used to define constant scalar values, they cannot be used directly to create NSNumber literals; for example, the following attempt to create an NSNumber literal from an enum (shown in Listing 16-9) will not compile.
Listing 16-9. Attempt to Create an NSNumber Literal from an enum
enum
{
Zero = 0,
One
};
NSNumber *zeroNumber = @Zero; // Error!
Instead, an enum value must be placed inside an expression literal (i.e., a boxed enum) to create anNSNumber instance. Listing 16-10 corrects the example shown in Listing 16-9 to create an NSNumberinstance from a boxed enum.
Listing 16-10. Creating an NSNumber from a Boxed enum
enum
{
Zero = 0,
One
};
NSNumber *zeroNumber = @(Zero); // Correct!
If an enum has a fixed underlying type (i.e., it specifies the type used to store its values), theNSNumber instance will be created with the corresponding type. The example shown in Listing 16-11creates an NSNumber instance from a boxed enum; as the enumeration is of type unsigned int, theNSNumber instance is created with the corresponding type.
Listing 16-11. Creating an NSNumber from a Boxed enum with a Fixed Underlying Type
enum : unsigned int
{
Zero = 0,
One
};
NSNumber *zeroNumber = @(Zero); // invokes [NSNumber numberWithUnsignedInt:]