Brief Intro to Expression Literals

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:]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值