標籤:字面量文法
字面量文法
第一、字面數值
複雜方法:
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,則會拋異常
使用字面量文法讓iOS代碼更漂亮