Fit*_*itz 4 xcode if-statement objective-c ios xcode4.2
我想在一周的每一天显示一个不同的网站.我创建了一个NSString,它使用NSDateFormatter只包含一周中的当前日期.然后,我为一周中的每一天创建了额外的字符串.我在"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];
Run Code Online (Sandbox Code Playgroud)
Dan*_*iel 11
以下是更好的解决方案,使用工作日的索引来确定您的网址:
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];
Run Code Online (Sandbox Code Playgroud)
要按照您对评论的要求刷新支票,您可以这样做:
在您的应用程序委托文件中,将此行添加到applicationDidBecomeActive:方法中
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDateCheck" object:nil];
}
Run Code Online (Sandbox Code Playgroud)
在您的班级中,您正在进行日期检查,在init方法中添加此行以收听应用程序退出后台时发送的任何刷新通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod) name:@"refreshDateCheck" object:nil];
Run Code Online (Sandbox Code Playgroud)
最后将日期检查代码移到此方法,该方法在收到通知时调用:
-(void)myMethod{
/*
Your other code goes in here
*/
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15559 次 |
| 最近记录: |