代码简写

@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 }

取key1值 :id value = dic[key1];


当写下@{ 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 ]
 取下标1的值 :id value = arr[1];
 
比如对于@[ 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];


另外,对于标记为static的数组,不能使用简写为其赋值(其实原来的传统写法也不行)。
如果直接赋值就会提示出错

static NSArray *  thePlanets = @[                                            error:array literals not constant
  @"Mercury", @"Venus", @"Earth",
  @"Mars", @"Jupiter", @"Saturn",
  @"Uranus", @"Neptune"
];

原文地址:https://www.cnblogs.com/swallow37/p/3867947.html