1. 程式人生 > >Objective-C代碼簡寫

Objective-C代碼簡寫

字典 iter har rcu 查找 bug turn 特性 很多

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
嗯…方便很多啊~以前最討厭的就是數字放Array裏還要封裝成NSNumber了…現在的話直接用@開頭接數字,可以簡化不少。

NSArray

部分NSArray方法得到了簡化:
  • [NSArray array] 簡寫為 @[]
  • [NSArray arrayWithObject:a] 簡寫為 @[ a ]
  • [NSArray arrayWithObjects:a, b, c, nil] 簡寫為 @[ a, b, c ]
需要特別註意,要是a,b,c中有nil的話,在生成NSArray時會拋出異常,而不是像[NSArray arrayWithObjects:a, b, c, nil]那樣形成一個不完整的NSArray。其實這是很好的特性,避免了難以查找的bug的存在。

NSDictionary

既然數組都簡化了,字典也沒跑兒,還是和Perl啊Python啊Ruby啊很相似,意料之中的寫法:
  • [NSDictionary dictionary] 簡寫為 @{}
  • [NSDictionary dictionaryWithObject:o1 forKey:k1] 簡寫為 @{ k1 : o1 }
  • [NSDictionary dictionaryWithObjectsAndKeys:o1, k1, o2, k2, o3, k3, nil] 簡寫為 @{ k1 : o1, k2 : o2, k3 : o3 }
Mutable版本和靜態版本 上面所生成的版本都是不可變的,想得到可變版本的話,可以對其發送-mutableCopy消息以生成一份可變的拷貝。比如 NSMutableArray *mutablePlanets = [@[ @"Mercury", @"Venus", @"Earth", @"Mars", @"Jupiter", @"Saturn", @"Uranus", @"Neptune" ] mutableCopy]; 另外,對於標記為static的數組(沒有static的字典..哈希和排序是在編譯時完成的而且cocoa框架的key也不是常數),不能使用簡寫為其賦值(其實原來的傳統寫法也不行)。解決方法是在類方法+ (void)initialize中對static進行賦值,比如: 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; </pre> - (void)setObject:(elementType)object atIndexedSubscript:(indexType)idx; 對於類似字典的結構: - (elementType)objectForKeyedSubscript:(keyType)key; </pre> - (void)setObject:(elementType)object forKeyedSubscript:(keyType)key;

Objective-C代碼簡寫