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

16,090

Solution 1

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
    */
}

Solution 2

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

Solution 3

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.

Solution 4

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 (...)

Solution 5

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.

Share:
16,090
Fitz
Author by

Fitz

Updated on June 26, 2022

Comments

  • Fitz
    Fitz almost 2 years

    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];
    
  • Fitz
    Fitz over 12 years
    See that now...thanks a lot. I guess staring at the page for a few hours made me miss it...regardless your answer explained the parts I didn't understand as well. Thanks!
  • Guillaume
    Guillaume over 12 years
    As with all bugs, it is obvious once you see it ;-) Check also the answer by @Paul.s he spotted an other bug.
  • Fitz
    Fitz over 12 years
    coming from no language at all! just learning now. Thanks...I'll check it out though.
  • Fitz
    Fitz over 12 years
    thanks! I'm just starting out, and corrections like this are extremely helpful. I'll update it to using the switch statement. One other question...say that someone opens the app the next day, will it automatically update to reflect the new day and the new code, or will the app have to be closed and opened?
  • Daniel
    Daniel over 12 years
    This is where he went wrong although I do suggest Fitz check out my solution as it isn't a very good idea to play around with strings for this kind of thing stackoverflow.com/a/8797061/662605
  • Daniel
    Daniel over 12 years
    That's my answer ;) I am also disappointed, but it was important to show his error also - stackoverflow.com/a/8797061/662605
  • Abizern
    Abizern over 12 years
    No - that's work you'll have to do yourself. Either by checking the date when the app displays, or by setting up handlers for the notifications of changes in date.
  • Daniel
    Daniel over 12 years
    You could handle the app launch and awake from background methods in the app delegate, triggering a notification allowing you to recheck the date and reload a different page if needed
  • Paul.s
    Paul.s over 12 years
    This is true but after skimming the NSCalendar class and coming up with the solution in my head, I thought the OP would probably benefit from the explanation of what they did wrong. To do that and then offer another solution would be a little over the top (judging by the original code provided). I do agree a different answer should be selected.
  • Fitz
    Fitz over 12 years
    I just made an account today so I don't have enough reputation to up vote..You were very helpful though...I'll be sure to follow some of your other answers as I keep trying to learn objective c...(and up vote you when I am eventually able to!)
  • Daniel
    Daniel over 12 years
    Just up voted your question, should give you a helping hand... Also about to update my answer for your refresh question in the other comment, don't hesitate to choose my answer as correct if you think it's better ;)
  • Daniel
    Daniel over 12 years
    Added refresh logic for you, have a nice day
  • Abizern
    Abizern over 12 years
    I'm not disputing the solutions. They are right, but most of us know the approach is wrong. And, if we don't point this out to new Cocoa programmers, who will? It's like being asked "Should I use a stone or a bottle to hammer a nail in the wall?" The answer to the question is "stone", but the real answer is to use a hammer. And we've all seen the "stone" answer get accepted on SO.
  • Fitz
    Fitz over 12 years
    Awesome I'll try it out. Thanks for all of the help!
  • Paul.s
    Paul.s over 12 years
    Being a bit anal but would it not look a lot nicer if you DRY it up slightly and in each case just assign a string e.g. urlAddress = @"http://google.com"; and then at the end of the switch you could do NSURL *url = [NSURL URLWithString:urlAddress];. At least then you only have URLWithString: written once, which is great if you decide to change the use of NSURL
  • Paul.s
    Paul.s over 12 years
    I guess what I should have done is to submit two answers at least then if people come to SO in future they will look for the accepted answer (for the hammer answer) but the description of other issues can be done somewhere else.
  • Daniel
    Daniel over 12 years
    Yea I would do that also to be honest, nice spot, I usually go back on my code and refine them like this, oh the joys of OCD...
  • Abizern
    Abizern over 12 years
    @Paul.s Multiple answers get merged in SO. That wouldn't work. You just answer both in one answer. In this case (and this is just my opinion) is to link to one of the many answers about value and pointer equality, and then given a proper answer.
  • Paul.s
    Paul.s over 12 years
    Also one more thing I would probably be defensive and add a default: case to set urlString = nil;. You never know you may modify code later on and foolishly make the value of weekday > 7.
  • Daniel
    Daniel over 12 years
    Are you suggesting Stack Overflow introduce a "Solution" answer and a "How it should be done" optional answer ? not a bad idea
  • Daniel
    Daniel over 12 years
    A switch should never not have a default, I was just thinking that but assumed weekday would always come from the NSDateComponents. Amended the code.
  • Paul.s
    Paul.s over 12 years
    @Daniel that wasn't what I was intending to suggest, I just assumed that if I answered twice they were kept separate (which I think would be cool). I think Abizern probably has the workable solution with providing links. Although if you are new and you don't really understand the basics it can be hard to see how another solution fits yours without the exact terms and structure of your problem being addressed.
  • Daniel
    Daniel over 12 years
    I agree, questions like these can be a little tedious to really grasp the wrongs and rights from the work arounds