字面量語法
第一、字面數值
復雜方法:
NSNumber *someNumber=[NSNumber numberWithDouble:3.4];
NSLog(@"the value is %@",someNumber);
替代方法:
NSNumber *
[email protected];
NSNumber *b=@32;
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 *arr1=@[@"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 *personDic=@{@"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]=@"andy";
NSLog(@"the first value is %@",arr1[0]);
第六、總結
1、使用字面量語法去創建對象,簡明而要
2、通過取下標操作來訪問數組與取key操作來訪問字典
3、用字面值語法創建數組或字典時,若值中有nil,則會拋異常