Fitz
Fitz

Reputation: 313

How to use "If" statements when comparing two strings in Objective C (Xcode)?

I am trying to display a different website on each day of the week. I created a NSString that contains just the current day of the week by using NSDateFormatter. Then, I created additional strings for each day of the week. I am comparing the two in an "IF" Statement...so if the strings (days) are equal, it will perform the function in the if statement. if not, it checks the next statement. Right now it will work for the first statement on Monday, but when I change the date on my iPhone to simulate other days of the week it won't work. My code is below!

NSDateFormatter *dayofweekformatter = [[NSDateFormatter alloc] init];
[dayofweekformatter setDateFormat:@"cccc"];

NSString *DayOfWeek = [dayofweekformatter stringFromDate:[NSDate date]];


NSString *Monday = @"Monday";
NSString *Tuesday = @"Tuesday";
NSString *Wednesday = @"Wednesday";
NSString *Thursday = @"Thursday";
NSString *Friday = @"Friday";
NSString *Saturday = @"Saturday";
NSString *Sunday = @"Sunday";



if ([DayOfWeek isEqualToString:Monday])

{ // Webview code

    NSString *urlAddress = @"http://www.google.com";

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Requst Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    //Load the request in the UIWebView.
    [webview loadRequest:requestObj];


}

else if (dateToday == Tuesday) 

{ // Webview code

    NSString *urlAddress = @"http://www.cnn.com";

    //Create a URL object.
    NSURL *url = [NSURL URLWithString:urlAddress];

    //URL Requst Object
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    //Load the request in the UIWebView.
    [webview loadRequest:requestObj];

Upvotes: 3

Views: 16545

Answers (6)

Paul.s
Paul.s

Reputation: 38728

Spot the difference

if ([DayOfWeek isEqualToString:Monday])  // 1
if (dateToday == Tuesday)                // 2
  1. In the first instance you call the isEqualToString: method therefore NSString compares the contents of the string for equality.

  2. In the second instance you use == this is a pointer comparison. The pointer Tuesday will point to a different object to that returned by [dayofweekformatter stringFromDate:[NSDate date]];

Therefore make sure you use the correct comparison methods for the type you are dealing with.

It's also worth nothing you are comparing different variable. In the first if you are comparing DayOfWeek in the second if you are comparing dateToday.

Update

It also looks like you may have come to Objective-C from a different language therefore it might be worth skimming the Apple docs for Coding Guidelines it just gives some quick examples of how things are generally named in Objective-C

Upvotes: 2

Daniel
Daniel

Reputation: 23359

A better solution would be the following, using the index of the weekday to determine your url:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger weekday   = [components weekday];
NSString *urlString;
switch(weekday){
    case 1: // sunday
        urlString = @"http://google.com";
        break;
    case 2:
        urlString = @"http://twitter.com";
        break;
    case 3:
        urlString = @"http://facebook.com";
        break;
    case 4:
        urlString = @"http://yahoo.com";
        break;
    case 5:
        urlString = @"http://mashable.com";
        break;
    case 6:
        urlString = @"http://bbc.co.uk";
        break;
    case 7: // saturday
        urlString = @"http://stackoverflow.com";
        break;
    default:
        urlString = @"http://google.com?q=weekday+is+never+this!";
        break;
}

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//Load the request in the UIWebView.
[webview loadRequest:requestObj];

To refresh your checks as you asked on a comment, you could do this:

In you application delegate file add this line to the applicationDidBecomeActive: method

- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDateCheck" object:nil];
}

Over in your class you are doing your date checking, in the init method add this line to listen out for any refresh notifications sent when the app comes out of the background:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod) name:@"refreshDateCheck" object:nil];

Finally move over your date check code to this method which is called whenever the notification is received:

-(void)myMethod{
    /* 
    Your other code goes in here
    */
}

Upvotes: 10

Abizern
Abizern

Reputation: 150605

I'm disappointed in all of you who answered til now.

Yes - you are correctly pointing out the difference between pointer equality and value equality.

But you aren't pointing out that the questioner is going the wrong way about testing for weekdays - which is the real question he asked.

A different solution to the actual problem:

You have a date - you can turn that into an NSDateComponents - which has a weekday method that returns an NSInteger which in the case of Gregorian - returns 1 for Sunday, 2 for Monday, etc.

For example - this is taken straight from the calendrical calculation section of the Apple docs

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];

Now you can just use a switch statement.

Upvotes: 2

jimmyg
jimmyg

Reputation: 580

You can use the @"E" date format to get the numeric day of the week. Now you are not tied to a language specific string.

NSDateFormatter *dayofweekformatter = [[NSDateFormatter alloc] init];
[dayofweekformatter setDateFormat:@"E"];

NSString *DayOfWeek = [dayofweekformatter stringFromDate:[NSDate date]];
NSInteger weekDay = [DayOfWeek integerValue];
switch (weekDay) {
    case 1: // Sunday
        break;

    case 2: // Monday
        break;

    default:
        break;
}

Upvotes: 3

esqew
esqew

Reputation: 44698

You're not handling any other case besides Monday correctly. You need to add more code like you had before (with isEqualToString instead of ==):

if ([DayOfWeek isEqualToString:Monday])

{ 
    /* code here */
}

else if ([DayOfWeek isEqualToString:Tuesday])

{ 
    /* code here */
}

else if ([DayOfWeek isEqualToString:Wednesday])

{ 
    /* code here */
}

else if (...)

Upvotes: 2

Guillaume
Guillaume

Reputation: 21736

You used isEqualToString for your first check, which is good, but then perform the next comparison using ==.
Use else if ([dateToday isEqualToString:tuesday])

Also, as a side note, your variable name should start with a lower case letter.

Upvotes: 3

Related Questions