简体   繁体   中英

Objective-C: Boxing VS Literal

Which construct should I use, why? I'll make an example with NSArray . The same apply to other "boxed" objects, such as NSDictionary , NSNumber ...

NSArray *arr1 = @[object1, object2, object3];

or

NSArray *arr2 = [NSArray arrayWithObjects:object1, object2, object3, nil];

The two constructs produce identical effect for NSArray and NSDictionary objects. The difference is that the first syntax is not available prior to the 2012 version of the compiler, while arrayWithObjects: works with all versions of the language.

If you are not planning for your code to compile with older versions of the complier, the new syntax is gives you better readability, especially for NSNumber objects. Compare

NSArray *arr = @[@1, @2, @3];

vs.

NSArray *arr = [NSArray arrayWithObjects:
    [NSNumber numberWithInteger:1]
,   [NSNumber numberWithInteger:2]
,   [NSNumber numberWithInteger:3]
,   nil
];

Neither NSArray nor NSDictionary literals are "boxed". Boxing refers to when you make objects out of scalars or non-object types. Cocoa arrays and dictionaries are always objects.

Boxing is the relevant terminology for NSNumber , though. For example, 1 is an int , a scalar type (not an object). @1 is an NSNumber , the result of boxing 1 . However, technically, I'd say that [NSNumber numberWithInt:1] is also boxing. It's just that @1 is a more convenient syntax.

There is a difference between:

NSArray *arr1 = @[object1, object2, object3];

and

NSArray *arr2 = [NSArray arrayWithObjects:object1, object2, object3, nil];

In the first, if any of object1 , object2 , or object3 hold nil , you will get a runtime exception. In the second, any nil just terminates the argument list. So, if object2 is nil , arr2 will end up as a single-element array holding only object1 . NSArray will never even get around to considering object3 because, as far as it's concerned, the argument list was terminated after the first element.

Rarely, you can make legitimate use of this behavior (in which case, I'd clearly make note of it in the comments), but most often this is unexpected and undesirable behavior. It's a particularly pernicious sort of bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM