An analysis of objective-c literal quantity

Source: Internet
Author: User

When you write a objective-c program, you always use a few classes, which belong to the foundation framework. While it is technically possible to write objective-c code without the foundation framework, it is often used in this framework. These classes are NSString, NSNumber, Nsarray, Nsdictionary. The data structure represented by the class name can be seen.

Objective-c is famous for its grammatical complexity. In fact, that's true. However, from Objective-c 1.0, there is a very simple way to create a NSString object. This is the string literal, which has the following syntax: literal
NSString *somestring = @ "effective OBJECTIVE-C 2.0";

If this syntax is not used, the NSString object must be allocated and initialized with the usual alloc and Init methods. In a newer version of the compiler, you can also use this literal syntax to declare instances of the NSNumber, Nsarray, and Nsdictionary classes. Use literal syntax (literal syntax) to reduce the length of the source code to make it easier to read.

Literal value

It is sometimes necessary to block integers, floating-point numbers, and Boolean values into Objective-c objects. In this case, you can use the NSNumber class, which can handle multiple types of numeric values. If you don't use the literal, you need to create the instance as follows:
NSNumber *somenumber = [NSNumber numberwithint:1];

The above line of code creates a number that sets its value to Integer 1. However, using literals can make your code more uncluttered:
NSNumber *somenumber = @1;

As you can see, the literal syntax is more streamlined. But it still has a lot of benefits. This syntax can be used by all data types that can be represented as nsnumber instances. For example:
NSNumber intnumber = @1;
NSNumber
floatnumber = @2.5f;
NSNumber doublenumber = @3.14159;
NSNumber
boolnumber = @YES;
NSNumber *charnumber = @ ' a ';

The literal syntax also applies to the following expressions:

It is useful to represent values in literal quantities. Doing so can make the NSNumber object neat, because the declaration contains only numeric values, and there is no extra syntactic component.

Literal array

Arrays are commonly used data structures. If you don't use literal syntax, you'll create an array like this:

Instead, the literal syntax is used to create:

The above approach is not only simple, but also beneficial for manipulating arrays. The common operation of an array is to take the object corresponding to a subscript, which is easier to do with the literal. If you don't use the literal, you'll usually use the "Objectatindex:" Method:

If the literal is used, it is:

This is also known as the "Take Off" operation (subscripting), which is more concise and easier to understand than other cases of using literal syntax, and is similar to the syntax used in other languages to access array elements by subscript.

However, when creating an array with literal syntax, it is important to note that if there is nil in the array element object, an exception is thrown because the literal syntax is actually just a "syntactic sugar" (syntactic sugar), whose effect is equal to creating an array first, and then adding all the objects inside the square brackets to the array. The exception that is thrown is this:

1
2
3
4
Terminating app due to uncaught exception
' Nsinvalidargumentexception ', Reason: ' * * *
-[__nsplaceholderarray Initwithobjects:count:]: Attempt to
Insert Nil object from objects[0] '

You will encounter this problem when you use literal syntax to create an array. The following code creates an array of two syntaxes, respectively:

1
2
3
4
5
6
7
 id object1 =/* ... */;  
id object2 =/* ... */;
id object3 =/* ... */;

nsarray *arraya = [Nsarray array withobjects:
                        Object1, Object2, object3, nil];
nsarray *arrayb = @[object1, Object2, object3];

People think: If Object1 and Object3 both point to a valid Objective-c object, and Object2 is nil, what happens? An exception is thrown when an array arrayb is created by literal syntax. Although Arraya can be created, it contains only Object1 objects. The reason is that the "arraywithobjects:" method processes each parameter in turn until nil is found and the method ends prematurely because Object2 is nil.

This subtle difference suggests that using literal syntax is more secure. Throwing an exception makes the application terminate execution, which is better than finding the number of elements after creating the array. Inserting nil into an array usually indicates that the program is wrong, and that the error can be discovered more quickly through an exception.

Literal dictionary

A "dictionary" (Dictionary) is a mapped data structure where you can add key-value pairs. As with arrays, the OBJECTIVE-C code is often used in dictionaries. It is created in the following way:

This is confusing because the order is < object >,< key >,< object >,< key >. This is in contrast to the usual order of understanding, which we generally think is to map "keys" to "objects". Therefore, this kind of writing is not easy to read. If you use literal syntax, it's much clearer:

The above is more concise, and the key appears before the object, the understanding is smoother. This sample code also illustrates the benefits of using literal values. The objects and keys in the dictionary must all be objective-c objects, so it is not possible to put the integer 28 directly in, but to encapsulate it in the NSNumber instance. It's easy to do this with literal syntax, just by adding an @ character to the number.

As with arrays, there is also a problem when creating a dictionary with literal syntax, that is, once the value is nil, an exception is thrown. But for the same reason, this is a good thing. If you accidentally use a null object when creating a dictionary, the "Dictionarywithobjectsandkeys:" Method stops before the first nil and throws an exception, which helps to check for errors.

Dictionaries can also be accessed in literal syntax like arrays. The traditional practice of accessing its values by a specific key is:

The equivalent literal syntax is:

This also eliminates the redundant syntax, making this line code easy to read.

Variable groups and dictionaries

By removing the label operation, you can access an element in the array that corresponds to a key in the index or dictionary. If the array and the Dictionary object are mutable (mutable), the element values can also be modified by subscript. The standard practice for modifying variable arrays and dictionary content is:

If you write by using the Remove label operation:

Limitations

There is a small limitation to the literal syntax, except that the object created must belong to the foundation framework in addition to the string. If you customize the subclasses of these classes, you cannot create their objects with literal syntax. To create an instance of a custom subclass, you must use the non-literal syntax (nonliteral syntax). However, since Nsarray, Nsdictionary, and NSNumber are all stereotyped "sub-families" (class cluster, see 9th), few would customize subclasses from them, and it would be more troublesome to do so. And in general, the standard implementation has been very good, no need to change. You can use a custom subclass when you create a string, but you must modify the compiler's options. Unless you understand the consequences of doing so, it is not encouraged to use this option, and nsstring is sufficient.

strings, arrays, and dictionary objects created using the literal syntax are immutable (immutable). If you want a variable version of an object, you need to copy it:

Doing so invokes a method and creates an object, but the benefit of using literal syntax is more than the above disadvantage.

Points

You should use literal syntax to create strings, numbers, arrays, dictionaries. This is more concise than the usual method of creating such objects.

The element that corresponds to the key in the array subscript or dictionary should be accessed by removing the label operation.

 When you create an array or dictionary with literal syntax, an exception is thrown if there is nil in the value. Therefore, it is important to ensure that the value does not contain nil.

An analysis of objective-c literal quantity

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.