使用字面量语法可以缩减源代码长度,是其更为易读。
注意事项:用字面量语法创建数组时要注意,若数组元素对象中有nil,则会抛出异常。用字面量数组创建数组,其效果等于是先创建了一个数组,然后把方括号内得所有对象都加到这个数组中。
例如:
id obj1 = @"obj1";
id obj2 = nil;
id obj3 = @"obj3";
NSArray *arrayA = [NSArray arrayWithObjects:obj1, obj2, obj3, nil];
NSArray *arrayB = @[obj1, obj2, obj3];
arrayA能创建出来,但是arrayB会抛出异常。因为,arrayWithObjects方法会依次处理各个参数,直到发现nil为止,遇到对象为nil时,该方法会提前结束。然而arrayB在遇到对象为nil时,会抛出异常。这个微妙得差别,使用字面量语法更为安全。抛出异常令应用程序终止执行,这比创建好数组之后才发现元素个数少了要好。向数组中插入nil通常说明程序有错,而通过异常可以更快地发现这个错误。
在创建字典时(NSDictionary),字典中的对象和键值必须都是OC对象。所以用字面量就比用非字面量方便很多了。例如用字面量语法生成字典:
NSDictionary *dic1 = @{ @"timestamp" : @"2014-09-25 00:00:00", @"relateProfit" : @9, @"relateSevenPercent" : @1234 };
用非字面量语法生成字典:
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2014-09-25 00:00:00", @"timestamp", [NSNumber numberWithFloat:9], @"relateProfit", [NSNumber numberWithFloat:1234], @"relateSevenPercent", nil];
要点:1.应该使用字面量语法来创建字符串、数值、数组、字典。与创建此类对象的常规方法相比,这么做更加简明扼要。
2.应该通过取下标操作来访问数组下标或字典中得键所对应的元素。
3.用字面量语法创建数组或字典时,若值中有nil,则会抛出异常。
int x = 6;
//非字面量语法
NSString *string = [NSString stringWithUTF8String:"Hello World"];
NSNumber *numberChar = [NSNumber numberWithChar:'X'];
NSNumber *numberInt = [NSNumber numberWithInt:12345];
NSNumber *numberInt1 = [NSNumber numberWithInt:6 + x * 2012];
NSNumber *numberUnsignedLong = [NSNumber numberWithUnsignedLong:12345ul];
NSNumber *numberLongLong = [NSNumber numberWithLongLong:12345ll];
NSNumber *numberFloat = [NSNumber numberWithFloat:123.45f];
NSNumber *numberDouble = [NSNumber numberWithDouble:123.45];
NSNumber *numberBool = [NSNumber numberWithBool:YES];
NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSString *str = [array objectAtIndex:1];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: @"v1", @"k1", @"v2", @"k2", nil];
NSString *strDic = [dic valueForKey:@"k1"];
//字面量语法
NSString *string_ = @"Hello World";
NSNumber *numberChar_ = @'X';
NSNumber *numberInt_ = @12345;
NSNumber *numberInt1_ = @(6+x*2012);
NSNumber *numberUnsignedLong_ = @12345ul;
NSNumber *numberLongLong_ = @12345ll;
NSNumber *numberFloat_ = @123.45f;
NSNumber *numberDouble_ = @123.45;
NSNumber *numberBool_ = @YES;
NSNumber *isStatusBarHidden = @([UIApplication sharedApplication].statusBarHidden);
NSNumber *numFloatY = @(APPDELEGATE.window.frame.size.width);
NSArray *array_ = @[@"a", @"b", @"c"];
NSString *str_ = array[1];
NSDictionary *dic_ = @{@"k1":@"v1", @"k2":@"v2"};
NSString *strDic_ = dic_[@"k1"];