首页 > 代码库 > Objective-C literal syntax
Objective-C literal syntax
1.NSNumber
old:NSNumber *oldNumber = [NSNumber numberWithInt:1];
new:NSNumber *newNumber = @1;
同理:
NSNumber *intNumber = @1;
NSNumber *floatNumber = @1.0f;
NSNumber *doubleNumber = @0.001;
NSNumber *boolNumber = @YES;
NSNumber *charNumber = @‘a‘;
2.NSArray
old:NSArray *oldArray = [NSArray arrayWithObjects:@"David",@"Tom",@"Jack",nil];
new:NSArray *newArray = @[@"David",@"Tom",@"Jack"];
old:NSString *Tom = [oldArray objectAtIndex:1];
new:NSString *Tom = newArray[1];
区别:
NSArray *oldArray = [NSArray arrayWithObjects:@"David",nil,@"Tom",@"Jack",nil];//创建成功,数组只含一个元素
NSArray *newArray = @[@"David",nil,@"Tom",@"Jack"];//创建失败,报错
3.NSDictionary
old:NSDictionary *oldDic = [NSDictionary dictionaryWithObjectsAndKeys:@"Eric",@"firstName",@"Yin",@"lastName",[NSNumber numberWithInt:16],@"age"];
new:NSDictionary *newDic = @{@"firstName":@"Eric",@"lastName":@"Yin",@"age":@26};
old:NSString *firstName = [oldDic objectForKey:@"firstName"];
new:NSString *firstName = newDic[@"firstName"];
4.NSMutableArray,NSMutableDictionary(setting)
old:
[mutableArray replaceObjectAtIndex:1 withObject:@"Jason"];
[mutableDic setObject:@"Tom" forKey:@"firstName"];
new:
mutableArray[1] = @"Jason";
mutableDic[@"firstName"] = @"Tom";