0

These lines of code are the problem:

case CostPeriodMonthly:
            NSRange days = [gregorian rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];

            [endDateComponents setDay:days.length];
            [endDateComponents setMonth:[todayComponents month]];
            [endDateComponents setYear:[todayComponents year]];
            break;

The first line using days is highlighted saying "Use of undeclared identifier days" but why? What do I miss here?

MichiZH
  • 5,587
  • 12
  • 41
  • 81
  • There should be indication in Xcode which part of the line is exactly wrong. – Volker Feb 16 '14 at 12:06
  • Yep, the first line using 'days', so [endDateComponents setDay:days.length]; and there 'days' is highlighted – MichiZH Feb 16 '14 at 12:07
  • possible duplicate of [Why do my switch cases sometime need braces in Objective-C?](http://stackoverflow.com/questions/17582061/why-do-my-switch-cases-sometime-need-braces-in-objective-c) – Martin R Feb 16 '14 at 12:22

1 Answers1

3

If you want to declare new variables in a case statement, you have to enclose the statements in a {} block:

case CostPeriodMonthly: {
            NSRange days = [gregorian rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];

            [endDateComponents setDay:days.length];
            [endDateComponents setMonth:[todayComponents month]];
            [endDateComponents setYear:[todayComponents year]];
            break;
}
Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116
  • Actually it is sufficient to add a semicolon after the case label. Introducing a scope with `{ ... }` might be necessary if you compile with ARC (see the "possible duplicate"). – Martin R Feb 16 '14 at 12:25