字面量语法
第一、字面数值
复杂方法:
NSNumber *someNumber=[NSNumber numberWithDouble:3.4];
NSLog(@"the value is %@",someNumber);
替代方法:
NSNumber *[email protected];
NSNumber *[email protected];
NSLog(@"the value is %@",a);
NSLog(@"the value is %@",b);
第二、字面数组
复杂方法:
NSArray *arr=[NSArray arrayWithObjects:@"hello",@"richard",@"yang", nil];
NSLog(@"the first object is %@",[arr objectAtIndex:0]);
替代方法
NSArray *[email protected][@"hello",@"richard",@"yang"];
NSLog(@"the first object is %@",arr1[1]);
注意事项:
用字面量语法创建数组时,若有元素对象为nil,则会抛出异常,而用arrayWithObjects创建,nil前面的数据可以正确创建
第三、字面量字典
复杂方法:
NSDictionary *personDic=[NSDictionary dictionaryWithObjectsAndKeys:@"richard",@"name",@"001",@"num", nil];
NSLog(@"name is %@",[personDic valueForKey:@"name
替代方法:
NSDictionary *[email protected]{@"name":@"richard",@"num":@"001"};
NSLog(@"the name is %@",personDic[@"name"]);
第四、常见可变对象
NSMutableArray *arr1=[@[@"hello",@"richard",@"yang"] mutableCopy];
使用字面量语法创建的可变对象时需要加上mutaleCopy
第五、使用字面量语法修改值
NSMutableArray *arr1=[@[@"hello",@"richard",@"yang"] mutableCopy];
NSLog(@"the first value is %@",arr1[0]);
arr1[0][email protected]"andy";
NSLog(@"the first value is %@",arr1[0]);
第六、总结
1、使用字面量语法去创建对象,简明而要
2、通过取下标操作来访问数组与取key操作来访问字典
3、用字面值语法创建数组或字典时,若值中有nil,则会抛异常