Init an NSMutableArray with integers & an unwanted type conversion of some sort

Go To StackoverFlow.com

0

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!

2012-04-04 00:50
by Bryan Hanson


1

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];
2012-04-04 00:59
by Manlio
Thank you. I should have been able to figure out the loop process. As to the 2nd question, I thought the object at the index would be an NSUInteger, since I put such at object in the array. Can you tell me why this thinking is wrong? Much appreciated - Bryan Hanson 2012-04-04 01:19
You didn't put an NSInteger into the array, you put an NSNumber into the array, so you should get it out like this: NSUInteger nC = [[noClks objectAtIndex:CAP]integerValue] - rdelmar 2012-04-04 03:38