代码改变世界

NSNumber,NSArray,NSDictionary简写

2015-09-28 17:09  唐不坏  阅读(405)  评论(0)    收藏  举报

NSNumber

[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 ]

对于@[ 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 }

和数组类似,当写下@{ 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:keys count:count];  

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

NSMutableArray *mutablePlanets = [@[  
                                  @"Mercury", @"Venus", 
                                  @"Earth", @"Mars", 
                                  @"Jupiter", @"Saturn", 
                                  @"Uranus", @"Neptune" ] 
                                  mutableCopy];

下标

[_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