Use literal syntax to reduce the length of the source code, which is easier to read.
Note: When creating an array with literal syntax, be aware that an exception is thrown if there is nil in the array element object. Creating an array with a literal array has the effect of creating an array first, and then adding all the objects inside the square brackets to the array.
For example:
ID obj1 = @ "Obj1";
ID obj2 = nil;
ID obj3 = @ "Obj3";
Nsarray *arraya = Nsarray *arraya = [Nsarray arraywithobjects:obj1, Obj2, obj3, nil];
Nsarray *arrayb = @[obj1, Obj2, obj3];
Arraya can be created, but Arrayb throws an exception. Because the Arraywithobjects method processes each parameter in turn until nil is found, the method ends prematurely when the object is nil. However, Arrayb throws an exception when it encounters an object that is nil. This subtle difference is more secure using literal syntax. 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.
When you create a dictionary (nsdictionary), the objects and key values in the dictionary must all be OC objects. So it's a lot easier to use literal than to use non-literal. For example, generate a dictionary with literal syntax:
Nsdictionary *dic1 = @{@ "timestamp": @ "2014-09-25 00:00:00", @ "Relateprofit": @9, @ "relatesevenpercent": @1234};
To generate a dictionary with non-literal syntax:
Nsdictionary *dic2 = [nsdictionary dictionarywithobjectsandkeys:@ "2014-09-25 00:00:00", @ "timestamp", [NSNumber Numberwithfloat:9], @ "Relateprofit", [NSNumber numberwithfloat:1234], @ "relatesevenpercent", nil];
Important: 1. You should use literal syntax to create strings, numbers, arrays, dictionaries. This is more concise than the usual method of creating such objects.
2. You should access the array subscript or the element that corresponds to the key in the dictionary by removing the label operation.
3. When creating an array or dictionary with literal syntax, an exception is thrown if there is nil in the value.
iOS: Multi-use literal syntax