关闭

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

标签: Effective ObjectiveCLiteral Syntax Abstr
801人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:267797次
    • 积分:5442
    • 等级:
    • 排名:第4892名
    • 原创:264篇
    • 转载:93篇
    • 译文:10篇
    • 评论:7条
    文章分类
    最新评论