i try to make an array that has the numbers from 1 to 30 using..
NSMutableArray *numberOfdaysInAMonth = [[NSMutableArray alloc] init ] ;
for ( i=0; i< 30; i++){
[numberOfdaysInAMonth addObject:[NSNumber numberWithInteger:i+1]];
NSLog (@"Element_numberofDaysinAMonth %i = %@", i, [numberOfdaysInAMonth objectAtIndex: i]);
}
and I have an array with 35 elements and they have the value of null:
NSMutableArray *latestArrayForMonth = [[NSMutableArray alloc]init ];
for ( i=0; i<36; i++){
[latestArrayForMonth addObject:[NSNull null]];
}
Now I want to insert the values from numberOfDaysInAMonth into the LatestArrayWithMonth statrting from index:1 using:
for (i = 0; i < 30; i++){
[latestArrayForMonth insertObject:[numberOfdaysInAMonth objectAtIndex:i] atIndex:1];
NSLog (@"Element_latestArrayForMonth %i = %@", i, [latestArrayForMonth objectAtIndex: i]);
}
Output on the Console is:
Element_latestArrayForMonth 0 = <null>
Element_latestArrayForMonth 1 = 2
Element_latestArrayForMonth 2 = 2
Element_latestArrayForMonth 3 = 2
Element_latestArrayForMonth 4 = 2
Element_latestArrayForMonth 5 = 2
.
.
.
Element_latestArrayForMonth 28 = 2
Element_latestArrayForMonth 29 = 2
Why am I getting all 2s on the output?
It’s because of this line:
Because you’re inserting the item
atIndex:1continuously, as the ‘i’ variable is increasing in the loop, so is the number of items in the array – so the logging of the item at index ‘i’ is always the same item.Please also check that inserting the object at index 1 is what you are wanting to do – Objective-C is a zero-indexed language, meaning that the first item in the array is at index 0.
You probably want to remove all the objects in the
latestArrayForMontharray and simply use theaddObjectmethod (or useaddObjectsFromArrayto quickly add all the items from the array).Also might be worthy investigating alternative approaches to having an array full of ’empty’ values – I’ve never seen a use case for this approach yet, better to have an empty array than an array full of ’empty’ values.
One other thing to note is that since you’re just storing primitive integer values, you may find NSIndexSet more applicable to use than NSArray (depends on the application of the posted code, but worth investigation).