Question

I'm new to iOS and i'm having a hard time getting months and years for a period of 2 yrs. i'm putting them into an NSArray. All I can get is one year, but beyond that, the years don't increment to reflect year change. Please help? Thanks

NSDate  *todayDate = [NSDate date];
NSDateComponents *todayComponents=[[NSCalendar currentCalendar]      components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:todayDate];
NSMutableArray  *monthNameArray   = [[NSMutableArray alloc] init];

int currentMonth = [todayComponents month];
int currentYear = [todayComponents year];
int nextYear = currentYear + 1;

int month = 1;
int year;
for(int m = currentMonth ; month <= 12; m++){

    int nextMonth = m % 12;

    if(nextMonth < currentMonth){
        year = nextYear;
    } else {
        year = currentYear;
    }
    NSString *allMonths = [NSString stringWithFormat:@"%@ %d",[[dateFormatter monthSymbols]objectAtIndex:nextMonth], year];
    [monthNameArray addObject:allMonths];
    month++;
Was it helpful?

Solution

The for loop exits before going through 12 iterations because it is initialized with currentMonth instead of 1, so the result is not getting the months in next year. In addition, the for loop does not increment beyond 12, so you won’t get more than 12 months — this is not two years.

int month = currentMonth-1; // Make zero-based for use with monthSymbols
int year = currentYear;
for(int m = 0 ; m < 24; m++){

    if (month > 11) 
    {
      // The month has transitioned to the next year
      month = 0;
      ++year;
    }
    NSString *allMonths = [NSString stringWithFormat:@"%@ %d",[[dateFormatter monthSymbols]objectAtIndex:month], year];
    [monthNameArray addObject:allMonths];
    month++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top