iOS:创建具有多个参数/语句的循环的最佳方法是什么?

时间:2021-12-07 03:50:00

Here's what I'm trying to do: I'm using the NSCalendar and NSDateComponents objects to create a loop that will display text and an image based on the date. So, in my viewdidload is this, pretty standard:

这是我正在尝试做的事情:我正在使用NSCalendar和NSDateComponents对象来创建一个循环,它将根据日期显示文本和图像。所以,在我的viewdidload中,这是非常标准的:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents =
[gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:today];
NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];

Then I take the ints from month and day and have this:

然后我从一个月和一天开始注意这个:

if (month == 1 && day ==1)
[do this] //display text
[do this] //display image

here's where I need help: I originally created this as an if-else construct:

这里是我需要帮助的地方:我最初创建它是一个if-else结构:

if (month == 1 && day == 1)
[do this]
[do this]
else if (month == 1 && day == 2)
[do this]
[do this]

but for some reason, as soon as I add the second statement I get an error (expected expression)

但由于某种原因,只要我添加第二个语句,我就会收到错误(预期的表达式)

so I changed it to:

所以我改成了:

if (month == 1 && day == 1)
[do this]
[do this]
if (month == 1 && day == 2)
[do this]
[do this]

but now my second statement is being invoked even when if should return 0

但是现在我的第二个语句被调用,即使if应该返回0

is there a better way to do this using switch? Is it possible to have more than one expression as part of switch?

使用开关有更好的方法吗?是否可以将多个表达式作为切换的一部分?

1 个解决方案

#1


2  

You should use curly brackets:

你应该使用大括号:

if (month == 1 && day == 1) {
    [do this]
    [do this]
} else if (month == 1 && day == 2) {
    [do this]
    [do this]
}

Or

要么

if (month == 1 && day == 1) {
    [do this]
    [do this]
}
if (month == 1 && day == 2) {
    [do this]
    [do this]
}

#1


2  

You should use curly brackets:

你应该使用大括号:

if (month == 1 && day == 1) {
    [do this]
    [do this]
} else if (month == 1 && day == 2) {
    [do this]
    [do this]
}

Or

要么

if (month == 1 && day == 1) {
    [do this]
    [do this]
}
if (month == 1 && day == 2) {
    [do this]
    [do this]
}