Objective-C literal syntax Summary

Source: Internet
Author: User
Tags pear

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];

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.