2

I am trying to do something I thought would be relatively simple and get the current day of the week, then make some checks against that day when buttons are tapped. to get the day of the week I have used the following code in my viewDidLoad method:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];

The code returns me two NSIntegers which are the current day of the week and the current day of the month, which is what I wanted. I now want to have a series of buttons, which when tapped displays a certain webpage in a UIWebView depending on the day of the week.

I was hoping to do a simple:

-(IBAction) btnClicked 
{
    if (weekday == 1)
    {
       //DO SOMETHING HERE
    {
}

But I can't seem to get access to the 'weekday' NSInteger which was created in the viewDidLoad method. Im sure I am missing something very simple. Any advice?

Paul Morris
  • 1,763
  • 10
  • 33
  • 47

1 Answers1

4

The problem is weekday is out of scope when you try to use it in the btnClicked method. Try creating a property for it in the interface section like this:

@property (nonatomic, retain) NSInteger weekday;

Then @synthesize in the implementation

Or alternatively just add it as an instance variable:

@interface class : NSObject {
    NSInteger weekday;
}
@end
danielbeard
  • 9,120
  • 3
  • 44
  • 58
  • +1 Don't forget to mention that the `NSInteger weekday = [weekdayComponents weekday];` should be changed to `weekday = [weekdayComponents weekday];` – Sergey Kalinichenko Jan 25 '12 at 00:52
  • hhmm, doing that does give me access to it, but it produces a host of warnings about comparison between pointer and integer. It also sets the NSInteger value to '0' which is no good. – Paul Morris Jan 25 '12 at 00:57
  • Sorry, forgot that NSInteger is just an integer instead of an object. I have updated my code to match. – danielbeard Jan 25 '12 at 00:59
  • Thanks Daniel and dasblinkenlight. I rectified my issue by create NSInteger weekday; in my .h and changing the NSDate code to simple weekday = [weekdayComponents weekday]; – Paul Morris Jan 25 '12 at 08:17