Effective Objective-C 2.0: Item 3: Prefer Literal Syntax over the Equivalent Methods

Item 3: Prefer Literal Syntax over the Equivalent Methods


第二点需要注意,元素值出现nil会throw Exception,相比,更安全(容易发现问题)。

1. 
The literal syntax also works for expressions:

int x = 5;
float y = 6.32f;
NSNumber *expressionNumber = @(x * y);





2.
However, you need to be aware of one thing when creating arrays using the literal syntax. If any of the objects is nil, an exception is thrown


NSArray *arrayA = [NSArray arrayWithObjects:
                       object1, object2, object3, nil];
NSArray *arrayB = @[object1, object2, object3];

Now consider the scenario in which object1 and object3 point to valid Objective-C objects, but object2 is nil. The literal array, arrayB, will cause the exception to be thrownHowever, arrayA will still be created but will contain only object1. The reason is that thearrayWithObjects: method looks through the variadic arguments until it hits nil, which is sooner than expected.

This subtle difference means that literals are much safer. It’s much better that an exception is thrown, causing a probable application crash, rather than creating an array having fewer than the expected number of objects in it. A programmer error most likely caused nil to be inserted into the array, and the exception means that the bug can be found more easily.


3.
Also, in the case of strings, arrays, and dictionaries, only immutable variants can be created with the literal syntax. If a mutable variant is required, a mutable copy must be taken, like so:

NSMutableArray *mutable = [@[@1, @2, @3, @4, @5] mutableCopy];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值