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?
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:
@1
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:
NSArray * array = @[ @1 , @2 , @3 , ... ] ;
Which would give you an array of numbers. You'd have to do this to use them though:
for ( NSNumber * number in array )
{
NSLog ( @"This value is %i" , (int)number.intValue ) ;
// Alternatively, which does the exact same thing:
NSLog ( @"This value is %i" , (int)[number intValue] ) ;
}
If you wanted to make it mutable:
NSMutableArray * array = [ @[@1,@2,@3] mutableCopy ] ;
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.
char const * str = "abc" ;
NSString * str = @"abc" ;
int i = 1 ;
NSNumber * i = @1 ;
int arr[] = { 1 , 2 , 3 } ;
NSArray * arr = @[ @1 , @2 , @3 ] ;
// note: there's no concept of a dictionary in C
NSDictionary * dict = @{ @"a":@1 , @"b":@2 } ;
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:
int i = 5 ;
NSNumber * ii = @(i) ;
char const* str = "abc" ;
NSString * string = @(str) ;
See this for more information: http://clang.llvm.org/docs/ObjectiveCLiterals.html
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 NSNumber
s:
NSMutableArray *arrayA=[@[@0,@1,@2,@3,@4,@5] mutableCopy];
Since the values inside the array are NSNumber
s, you would need to unwrap them if you want to get integers by calling intValue
on them.