Prefer Literal Syntax over the Equivalent Methods
- Now consider the scenario in which object1 and object3 point to valid Objective-C objects, but object2 is nil. The literal array, arrayB, will cause the exception to be thrown. However, arrayA will still be created but will contain only object1. The reason is that the arrayWithObjects:method looks through the variadic arguments until it hits nil, which is sooner than expected.如果object2为nil,arrayA仍然会被创建但是里面的值只有objest1,arrayB则会抛出错误。
id object1 = /* ... */; id object2 = /* ... */; id object3 = /* ... */; NSArray *arrayA = [NSArray arrayWithObjects: object1, object2, object3, nil]; NSArray *arrayB = @[object1, object2, object3]; Mutable Arrays and Dictionaries
Methods传统的方法
[mutableArray replaceObjectAtIndex:1 withObject:@"dog"]; [mutableDictionary setObject:@"Galloway" forKey:@"LastName"];Literal Syntax通过下标的形式的简洁的代码
mutableArray[1] = @"dog"; mutableDictionary[@"lastName"] = @"Galloway";- In the case of strings, arrays, and dictionaries, only immutable variants can be created with the literal syntax. If a mutable variant is required, a mutable copy must be taken, like so:
NSMutableArray *mutable = [@[@1, @2, @3, @4, @5] mutableCopy];