Reputation: 21
There are lots of examples on this site about adding to NSMutableArray and I have looked at many but I still don't either understand (highly possible) or am missing something fundamental.
I am trying to add to an NSMutableArray via a for loop. I want to keep track of button x,y coordinate position using the button tag as key/index so I can change a button as a user clicks it. This is all without IB.
My init is as follow:
self.tmpXpos = [[NSMutableArray alloc] init];
self.tmpYpos = [[NSMutableArray alloc] init];[self.tmpXpos insertObject:[NSNull null] atIndex:0];
[self.tmpYpos insertObject:[NSNull null] atIndex:0];
**I added these after reading about 'creating' the array and populating it with null.
In the loop:
NSUInteger btag = button.tag; //NSUInterger as per help
>>NSNumber *xNumber = [NSNumber numberWithInteger:[self xpos]]; // NSNumber as an Object wrapper
>>NSNumber *yNumber = [NSNumber numberWithInteger:[self ypos]];
>>[self.tmpXpos insertObject:xNumber atIndex:btag];
>>[self.tmpYpos insertObject:yNumber atIndex:btag];
NSLog(@"%d, %@, %@",btag,xNumber,yNumber);
The log entries look ok:
2,64,0
3,128,0
etc for each button to be added to the screen.
During debugging - the tmpXpos and tmpYpos listed as " 0 Objects " under self.
I retrieve the information thusly:
NSUInteger tmpSt = [self.sTags integerValue];
NSNumber *tmpX = [self.tmpXpos objectAtIndex:tmpSt];
NSNumber *tmpY = [self.tmpYpos objectAtIndex:tmpSt];
int tmpPositionX = [tmpX intValue];
int tmpPositionY = [tmpY intValue];
NSLog(@"%d, %d",tmpPositionX, tmpPositionY);
NSLog yields 0, 0
I do appreciate any guidance or questions you folks might have as this site's 'sanity checks' have saved my bacon in the past.
I am ignoring memory leaks as of yet, but they are in the back of my mind. No worries there. Ironically, I have a couple of other arrays that work just fine, but the exception is that they are not populated via a loop.
Lastly, the code works fine as the button at location 0,0 does change as per design, LOL, but not for any other location.
Thanks again!
Neil
Upvotes: 0
Views: 964
Reputation: 21
Trees for the forest answer. I wanted to populate an array with a quantity, however, the array expects that quantity to be in numerical sequence. My data didn't have any 'gaps' but wasn't in sequence either; I.E., 1,2,3,6,7,12 etc. So, as user397313 helped me see, NSDictionary is the way to go with that kind of datum.
Upvotes: 0
Reputation: 2859
I think your problem is that you are creating the NSNumbers with the method numberWithInteger, when an NSUInteger is actually an unsigned long. So try
xNumber = [NSNumber numberWithUnsignedLong:[self xpos]];
Upvotes: 0