Effective Objective-C 2.0 Reading Notes

本文深入探讨了Objective-C中的字面量语法,包括字符串、数字、数组和字典的字面量创建方式,以及使用字面量时需要注意的特殊情况,如处理nil值时的异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Literal Syntax

 

NSString *someString = @"Effective Objective-C 2.0";

 

NSNumber *someNumber = [NSNumber numberWithInt:1];

<=>

NSNumber *someNumber = @1;

 

// syntax also works for expressions

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

 

NSArray *animals =
[NSArray arrayWithObjects:@"cat", @"dog",
@"mouse", @"badger", nil];

<=>

NSArray *animals = @[@"cat", @"dog", @"mouse", @"badger"];

 

NSString *dog = [animals objectAtIndex:1];

<=>

NSString *dog = animals[1];

 

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

 

a scenario:

id object1 = /* ... */;
id object2 = /* ... */;
id object3 = /* ... */;


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 thrown.
However, arrayA will still be created but will contain only object1. The reason is that the
arrayWithObjects: method looks through the variadic arguments until it hits nil, which is
sooner than expected.

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.

 

 

// Literal Dictionaries

NSDictionary *personData =
[NSDictionary dictionaryWithObjectsAndKeys:
@"Matt", @"firstName", @"Galloway", @"lastName",
[NSNumber numberWithInt:28], @"age", nil];

<=>

NSDictionary *personData =
@{@"firstName" : @"Matt",
@"lastName" : @"Galloway",
@"age" : @28};

 

NSString *lastName = [personData objectForKey:@"lastName"];

<=>

NSString *lastName = personData[@"lastName"];

 

 

 

转载于:https://www.cnblogs.com/davidgu/p/3731526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值