[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
[NSArray]
[NSArray array] //简写为 @[]
[NSArray arrayWithObject:a] //简写为 @[ a ]
[NSArray arrayWithObjects:a, b, c, nil] //简写为 @[ a, b, c ]
// compiler generates: 实际编译
id objects[] = { a, b, c };
NSUInteger count = sizeof(objects)/ sizeof(id);
array = [NSArray arrayWithObjects:objects count:count];
需要特别注意,要是a,b,c中有nil的话,在生成NSArray时会抛出异常,而不是像[NSArray arrayWithObjects:a, b, c, nil]那样形成一个不完整的NSArray。其实这是很好的特性,避免了难以查找的bug的存在。
[NSDictionary ]
[NSDictionary dictionary] //简写为 @{}
[NSDictionary dictionaryWithObject:o1 forKey:k1] //简写为 @{ k1 : o1 }
[NSDictionary dictionaryWithObjectsAndKeys:o1, k1, o2, k2, o3, k3, nil] //简写为 @{ k1 : o1, k2 : o2, k3 : o3 }
// compiler generates:
id objects[] = { o1, o2, o3 };
3
id keys[] = { k1, k2, k3 };
4
NSUInteger count = sizeof(objects) / sizeof(id);
5
dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
Mutable版本和静态版本
NSMutableArray *mutablePlanets = [@[@"Mercury", @"Venus",@"Earth", @"Mars",@"Jupiter",@"Saturn",
@"Uranus", @"Neptune" ]mutableCopy];
//对于标记为static的数组(没有static的字典,哈希和排序时在编译时完成的而且cocoa框架的key也不是常数),不能使用简写为其赋值(其实原来的传统写法也不行)。解决办法是在类方法+(void)initialize中对stayic进行赋值,比如:
static NSArray *thePlanets;
+ (void)initialize {
if (self == [MyClass class]) {
thePlanets = @[ @"Mercury", @"Venus", @"Earth", @"Mars", @"Jupiter", @"Saturn", @"Uranus", @"Neptune" ];
}
}
下标
// 使用简写的一大目的是可以使用下标来访问元素
[array objectAtIndex:idx] //简写为 array[idx];
[array replaceObjectAtIndex:idx withObject:newObj] //简写为 array[idx] = newObj
[dic objectForKey:key] //简写为 dic[key]
[dic setObject:object forKey:key] //简写为 dic[key] = newObject
//很方便,但是一定需要注意,对于字典用的也是方括号[],而不是想象中的花括号{}。估计是想避免和代码块的花括号发生冲突吧…简写的实际工作原理其实真的就只是简单的对应的方法的简写,没有什么惊喜。 但是还是有惊喜的..那就是使用类似的一套方法,可以做到对于我们自己的类,也可以使用下标来访问。而为了达到这样的目的,我们需要实现以下方法, 对于类似数组的结构:
- (elementType)objectAtIndexedSubscript:(indexType)idx;
- (void)setObject:(elementType)object atIndexedSubscript:(indexType)idx;
// 对于类似字典的结构
- (elementType)objectForKeyedSubscript:(keyType)key;
- (void)setObject:(elementType)object forKeyedSubscript:(keyType)key;