Is this format not allowed in Objective C?
NSMutableArray arrayA=[0,1,2,3,4,5];
is the only way to do this by adding one integer at a time?
Is this format not allowed in Objective C?
NSMutableArray arrayA=[0,1,2,3,4,5];
is the only way to do this by adding one integer at a time?
Sergey Kalinichenko
On
You cannot do it because integers are primitives, and NSArray and NSMutableArray cannot store primitives. You can do it by using the literal syntax that creates NSNumbers:
NSMutableArray *arrayA=[@[@0,@1,@2,@3,@4,@5] mutableCopy];
Since the values inside the array are NSNumbers, you would need to unwrap them if you want to get integers by calling intValue on them.
Copyright © 2021 Jogjafile Inc.
There are two parts to this question:
Integers are value-types and NSMutableArray can only have object-types in it.
As another comment said, there's a magic syntax:
Which says "I know this is a primitive, but please oh mighty compiler auto-magically make it an object for me."
Similarly, there's this syntax:
Which converts a C-array to an Objective-C NSArray [subclass].
So you could do this:
Which would give you an array of numbers. You'd have to do this to use them though:
If you wanted to make it mutable:
Other languages (like Python) have the syntax you want built-in because they are their own language and can internally represent anything as an object-type or value-type. They don't have to distinguish between them, and they pay the cost in terms of optimizability.
Objective-C is based on C and must still conform to C. Furthermore, the syntax must still conform to C, and number and [] tokens have specific meanings in C and C++ so they can't just re-define them. Therefore, they used their favorite syntax: the '@' sign, patterning it after strings.
This is often called "boxing" because you're boxing up a primitive into an object.
Note that the inner part for a number doesn't necessarily have to be a literal:
See this for more information: http://clang.llvm.org/docs/ObjectiveCLiterals.html