allItems is an NSMutableArray and when the user clicks the plus button the method createItem gets called. I’m trying to only add objects (of the class BNRItem) for every even number index, so I tried putting an instance of NSNull for the odd number indexes:
-(BNRItem *)createItem {
BNRItem *p = [[BNRItem alloc] init];
if ([allItems count] == 0)
[allItems addObject: p];
else {
[allItems addObject: [NSNull null]];
[allItems addObject: p];
}
return p;
}
And the output after I clicked the plus button 3 times is this:
2012-09-03 13:20:13.876 Homepwner[718:f803] Index: 0 item: Laptop (123): Worth $60, recorded on (September)
2012-09-03 13:20:13.876 Homepwner[718:f803] Index: 1 item: <null>
2012-09-03 13:20:13.877 Homepwner[718:f803] Index: 2 item: Brush (234): Worth $14, recorded on (September)
2012-09-03 13:20:13.882 Homepwner[718:f803] Index: 1 item: <null>
2012-09-03 13:20:13.882 Homepwner[718:f803] Index: 4 item: Calculator (345): Worth $19, recorded on (September)
If I keep clicking the plus button the <null> object always remains at index 1 instead of incrementing to 3, 5, and so on. I was wondering why it’s like this and how I can fix it.
You’re not showing the code for your logging, but, based on the results, I’d say you’re doing something like:
The
indexOfObject:method finds the lowest index whereobjis equal to an item in the array. Since[NSNull null]always gives you the same object (it’s a singleton), whenobjin the loop is theNSNull,indexOfObject:will always stop searching at 1.The
for–inloop will always go through your array in order, so you can just keep a counter to print the current index:or use a “regular”
forloop:Finally, the array will print itself and send
descriptionto each of its contained items if you just log it:NSLog(@"%@", arr);. This will be in order, so unless you really need the indexes attached, I’d suggest that.