Why can't I access the elements of my NSMutableArray?

140 views Asked by At

I declared arrays a,b,c and d as properties in my interface class and initialized them like this:

[self setPatternA:[[NSMutableArray init] initWithArray:@[@0,@0,@1,@1,@2,@2]]];
[self setPatternB:[[NSMutableArray init] initWithArray:@[@3,@4,@4,@5,@5,@3]]];
[self setPatternC:[[NSMutableArray init] initWithArray:@[@3,@3,@4,@4,@5,@5]]];
[self setPatternD:[[NSMutableArray init] initWithArray:@[@0,@1,@1,@2,@2,@0]]];

and now I'm trying to access them like this:

NSInteger a=[patternA objectAtIndex:3];
NSLog(@"pattern a: %ld", (long)a);

but when i print what this returns it isn't the value that I'm expecting. I am also getting a "Incompatible pointer to integer conversion initializing 'NSInteger' (aka 'long') with an expression of type 'id'.

Also, if someone could explain what a 'long' is, that'd be great.

2

There are 2 answers

2
Eiko On BEST ANSWER

You don't put integers, or NSIntegers, into the array, but objects, i.e. instances of NSNumber.

NSNumber *number = patternA[3];
long a = number.longValue;

will give give you correct value.

This is called boxing / unboxing - putting plain values into objects. So what you were dumping was more or less the address of the containing object.

0
Flexicoder On

Your arrays contain NSNumber - @1 is a NSNumber Literal. http://clang.llvm.org/docs/ObjectiveCLiterals.html

a long can hold a larger number than an int, but also takes up more bytes in memory http://code.tutsplus.com/tutorials/objective-c-succinctly-data-types--mobile-21986