Generally, you need to write some long method names when creating arrays and dictionaries. Today we will summarize how to replace these methods with literal syntax.
1. Create a value
NSNumber * number1 = [NSNumber numberWithInt: 1]; // the traditional method NSNumber * number2 = @ 1; // literal creation method
The traditional creation method is replaced by only one @, which looks elegant and neat.
NSNumber *intNumber = @1; NSNumber *floatNumber = @1.5f; NSNumber *boolNumber = @YES; NSNumber *charNumber = @'b';
2. Create an array
NSArray * fruits = [NSArray arrayWithObjects: @ "apple", @ "orange", @ "pear", nil]; NSArray * fruitss = @ [@ "apple ", @ "orange", @ "pear"]; // use [] to create an array
If nil occurs to an element when an array is created literally, an exception is thrown and the program is terminated. If an array is created in traditional mode, no error is reported. When an array is created, nil is processed in sequence. Therefore, we can detect errors in advance and create arrays using words to ensure security.
3. Create a dictionary
NSDictionary *userNameDic = [NSDictionary dictionaryWithObjectsAndKeys:@"mu",@"firstName",@"tou",@"lastName",nil]; NSDictionary *userNameDicc = @{@"firstName":@"mu",@"lastName":@"tou"};
It can be seen that the dictionary created by the new syntax is in line with people's reading habits, where the key is left and the value is right. However, when creating the dictionary, you must note that the key and value must be objects, the C language type cannot be put in. It should be converted to NSNumber and saved.
How to access dictionary values
NSString *lastName = [userNameDic objectForKey:@"lastName"];
NSString *lastName = userNameDicc[@"lastName"];
4. The objects created using the literal syntax are immutable. to change to a mutable object, perform the following conversions:
NSMutableArray *fruits = [@[@"apple",@"orange",@"pear"] mutableCopy];