I want to init a NSMutableArray with 8 integers. What I found in the SO archives strikes me as nuts, but it does seem to work:
_noClicks = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1], [NSNumber numberWithUnsignedInteger:1],nil];
I know Objective-c isn't a science-oriented language, but there must be a better way to do this (I guess that's Question 1). This code by the way is in the init
method of a singleton called GameData, and is put in a dictionary with other arrays.
Later, I use this array of integers as follows:
- (IBAction)buttonOneWasTouched:(id)sender {
NSUInteger CAP = [[GameData gameData] getCurAnsPos];
NSLog(@"%i", CAP); // CAP is current answer position and this seems to work
NSMutableArray *noClks = [[GameData gameData].curData valueForKey:@"noClicks"];
NSLog(@"%@", noClks); // gives the expected array of 1's
NSLog(@"%@", [noClks class]); // _NSArrayM OK I think
NSUInteger nC = [noClks objectAtIndex:CAP];
NSLog(@"%i", nC); // This gives a crazy answer: 109613120
}
So something is wrong here; the huge number that is logged for nC
suggests to me that it has been stored as other than an unsigned integer, but I don't see why. So this is Question #2.
Finally, and this is probably the clue, the compiler gives a warning Incompatible pointer to integer conversion initializing 'NSUInteger' (aka 'unsigned int') with an expression of type 'id';
at the 2nd to last line, but strangely, the 1st line has the same construction but doesn't give an error. This must be something ridiculously simple, all my recent questions have been. TIA!
For the first question, I'd suggest something like
_noClicks = [[NSMutableArray alloc] initWithCapacity:n];
for(int i=0;i<n;i++)
[_noClicks addObject:[NSNumber numberWithInt:1]];
As the name of the method suggests, objectAtIndex
returns an object, not a NSUInteger
. You may do something like
NSNumber *nC = [noClks objectAtIndex:CAP];
or
NSUInteger nC = [[noClks objectAtIndex:CAP] intValue];