iOS 简写 (iOS6 语法)

@literals(简写)

在xcode4.4以前
NSNumber
所有的[NSNumber numberWith…:]方法都可以简写了:
●  [NSNumber numberWithChar:‘X’]简写为 @‘X’;
●  [NSNumber numberWithInt:12345] 简写为 @12345
●  [NSNumber numberWithUnsignedLong:12345ul] 简写为 @12345ul
● [NSNumber numberWithLongLong:12345ll] 简写为 @12345ll
●  [NSNumber numberWithFloat:123.45f] 简写为 @123.45f
●  [NSNumber numberWithDouble:123.45] 简写为 @123.45
●  [NSNumber numberWithBool:YES] 简写为 @YES
 
NSDictionary
●  [NSDictionary dictionary] 简写为 @{}
●  [NSDictionary dictionaryWithObject:o1forKey:k1] 简写为 @{ k1 : o1 }
●  [NSDictionarydictionaryWithObjectsAndKeys:o1, k1, o2, k2, o3, k3, nil] 简写为 @{ k1 : o1, k2 : o2, k3 : o3 }
 
 
当写下@{ k1 : o1, k2 : o2, k3 : o3 }时,实际的代码会是
// compiler generates:
id objects[] = { o1, o2, o3 };
id keys[] = { k1, k2, k3 };
NSUInteger count = sizeof(objects) / sizeof(id);
dict = [NSDictionary dictionaryWithObjects:objects forKeys:keyscount:count];
 
NSArray
部分NSArray方法得到了简化:
● [NSArray array] 简写为 @[]
●  [NSArray arrayWithObject:a] 简写为 @[ a ]
●  [NSArray arrayWithObjects:a, b, c, nil] 简写为 @[ a, b, c ]

 

比如对于@[ a, b, c ],实际编译时的代码是
// compiler generates:
id objects[] = { a, b, c };
NSUInteger count = sizeof(objects)/ sizeof(id);
array = [NSArray arrayWithObjects:objectscount:count];


Mutable版本和静态版本
上面所生成的版本都是不可变的,想得到可变版本的话,可以对其发送-mutableCopy消息以生成一份可变的拷贝。比如

NSMutableArray *mutablePlanets = [

@[ 
                                  @"Mercury", @"Venus", 
                                  @"Earth", @"Mars", 
                                  @"Jupiter", @"Saturn", 
                                  @"Uranus", @"Neptune" 

   ]  mutableCopy];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值