在 Objective C (Xcode) 中比较两个字符串时如何使用“If”语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8796927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:57:23  来源:igfitidea点击:

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

objective-ciosxcodeif-statementxcode4.2

提问by Fitz

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 创建了一个只包含当前日期的 NSString。然后,我为一周中的每一天创建了额外的字符串。我在“IF”语句中比较两者...所以如果字符串(天)相等,它将执行 if 语句中的功能。如果不是,它检查下一个语句。现在它适用于星期一的第一条语句,但是当我更改 iPhone 上的日期以模拟一周中的其他日子时,它将不起作用。我的代码在下面!

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

回答by Daniel

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

在您的应用程序委托文件中,将此行添加到 applicationDidBecomeActive: 方法

- (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:

在您的课程中,您正在进行日期检查,在 init 方法中添加此行以侦听应用程序退出后台时发送的任何刷新通知:

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

回答by jimmyg

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.

您可以使用@"E" 日期格式来获取星期几。现在您不再绑定到特定于语言的字符串。

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

回答by Guillaume

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

您用于isEqualToString第一次检查,这很好,但随后使用==.
else if ([dateToday isEqualToString:tuesday])

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

另外,作为旁注,您的变量名称应以小写字母开头。

回答by Paul.s

Spot the difference

指出不同

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

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

  1. 在第一个实例中,您调用该isEqualToString:方法因此NSString比较字符串的内容是否相等。

  2. 在第二种情况下,您使用的==是指针比较。指针Tuesday将指向与返回的对象不同的对象[dayofweekformatter stringFromDate:[NSDate date]];

Thereforemake 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 ifyou are comparing DayOfWeekin the second ifyou are comparing dateToday.

您比较不同的变量也毫无价值。第一个if是比较DayOfWeek,第二个if是比较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 Guidelinesit just gives some quick examples of how things are generally named in Objective-C

看起来您可能是从不同的语言来到 Objective-C 的,因此可能值得浏览 Apple 文档的Coding Guidelines它只是提供了一些关于事物在 Objective-C 中通常如何命名的快速示例

回答by esqew

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

除了星期一之外,您没有正确处理任何其他情况。您需要像以前一样添加更多代码(用isEqualToString代替==):

if ([DayOfWeek isEqualToString:Monday])

{ 
    /* code here */
}

else if ([DayOfWeek isEqualToString:Tuesday])

{ 
    /* code here */
}

else if ([DayOfWeek isEqualToString:Wednesday])

{ 
    /* code here */
}

else if (...)

回答by Abizern

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 weekdaymethod that returns an NSInteger which in the case of Gregorian - returns 1 for Sunday, 2 for Monday, etc.

你有一个日期 - 你可以把它变成一个NSDateComponents- 它有一个weekday返回 NSInteger的方法,在格里高利的情况下 - 星期日返回 1,星期一返回 2,等等。

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

例如 - 这直接取自 Apple 文档的日历计算部分

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.

现在您可以只使用 switch 语句。